问题
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