PHP textfile value to array

自作多情 提交于 2021-02-11 12:50:13

问题


I have $data variable like this:

$data = [  'name'                => $name,
           'student_id'          => $student_id,
       ];

and I want to save it to text file:

$path = storage_path('app/public/').'student.txt';

        if (is_file($path)) {
            
            $path_ = Storage::disk('public')->prepend('data.txt', json_encode($data).',');
        } else {
            
            $path_ = Storage::disk('public')->put('data.txt', json_encode($data).',');
        }

and then I want to see the output:

$json = (Storage::disk('public')->get('data.txt'));
return $json;

and the value is:

{"name":"Michaela","student_id":"1202"},
{"name":"Zach","student_id":"1524"},

I want to have the output like this:

{
    {"name":"Michaela","student_id":"1202"},
    {"name":"Zach","student_id":"1524"},
}

So whenever hit this function, new array will append inside { } .. how can i achieve that?


回答1:


the output you are needing is actually not valid JSON. the valid format would be,

[
   {"name":"Michaela","student_id":"1202"},
   {"name":"Zach","student_id":"1524"},
]

to get this format change your code to following

$data[] = [
      'name'=> $name,
      'student_id'=> $student_id,
];

for example,

$data[] = [
      'name'=> 'A',
      'student_id'=> 'a',
];
$data[] = [
      'name'=> 'B',
      'student_id'=> 'b',
];

Before Saving to the file, encode the $data varibale in json,

$jsondata = json_encode($data);


来源:https://stackoverflow.com/questions/66036429/php-textfile-value-to-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!