This is my request:
https://localhost/profiles?id=1,2
i want to have an output of this:
"data": [
{
"id": 1
},
{
"id": 2
}
]
You can do it like below:-
$data = explode(',', $_GET['id']);
$data =array_map(function($item){
return ['id' => $item];
},$data);
echo json_encode(['data' => $data]);
Try this :-
$data = array('data' => array());
foreach(explode(',', $_GET['id']) as $key => $val){
$data['data'][$key]['id'] = $val;
}
print_r(json_encode($data));
You can do that in more laravel way as well for more cleaner solution.
$data = explode(',', $request->input('id'));
$data = collect($data)->map(function($item){
return ['id' => $item];
});
dd(json_encode(['data' => $data]));
在这种特殊的简单情况下,您也可以使用preg_replace
:
printf('{"data":[%s]}', preg_replace('~(\d+)~', '{"id"=$1}', $_GET['id']));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.