"forms": [
{
"id": 1,
"name": "new_patient",
"deleted_at": null,
"created_at": "2017-10-24 05:12:24",
"updated_at": "2017-10-24 05:12:24",
"pivot": {
"institution_id": 1,
"form_id": 1,
"field_name_id": 21,
"field_caption": "Gön.Hekim"
}
},
{
"id": 1,
"name": "new_patient",
"deleted_at": null,
"created_at": "2017-10-24 05:12:24",
"updated_at": "2017-10-24 05:12:24",
"pivot": {
"institution_id": 1,
"form_id": 1,
"field_name_id": 22,
"field_caption": "Kurum"
}
},
{
"id": 1,
"name": "new_patient",
"deleted_at": null,
"created_at": "2017-10-24 05:12:24",
"updated_at": "2017-10-24 05:12:24",
"pivot": {
"institution_id": 1,
"form_id": 1,
"field_name_id": 23,
"field_caption": "Endikasyon"
}
},
{
"id": 2,
"name": "edit_patient",
"deleted_at": null,
"created_at": "2017-10-24 05:12:24",
"updated_at": "2017-10-24 05:12:24",
"pivot": {
"institution_id": 1,
"form_id": 2,
"field_name_id": 24,
"field_caption": "Materyal"
}
}
]
I want to group forms object in same name/id.
How i want...
"forms": [
{
"id": 1,
"name": "new_patient",
"deleted_at": null,
"created_at": "2017-10-24 05:12:24",
"updated_at": "2017-10-24 05:12:24",
"fields": [{
"field_name_id": 21,
"field_caption": "Gön.Hekim"
},{
"field_name_id": 22,
"field_caption": "Kurum"
},{
"field_name_id": 23,
"field_caption": "Endikasyon"
}]
},
{
"id": 2,
"name": "edit_patient",
"deleted_at": null,
"created_at": "2017-10-24 05:12:24",
"updated_at": "2017-10-24 05:12:24",
"fields": [{
"field_name_id": 24,
"field_caption": "Materyal"
}]
}
]
i searched in so and googled, but i could not find any method for my problem. There are answers to similar questions.
i did with foreach loop but i thought may be there is a method for this in php.
And also, if i have over an hundred objects in json, foreach can be slow.
Thanks in advice.
Try the following:
$arr = json_decode($str, true);
$arr2 = [];
$ids = [];
foreach($arr['forms'] as $form)
{
if(!in_array($form['id'], $ids))
{
$ids[] = $form['id'];
$arr2[$form['id']] = $form;
}
unset($arr2[$form['id']]['pivot']);
$arr2[$form['id']]['fields'][] = [$form['pivot']['field_name_id'], $form['pivot']['field_caption']];
}
$str2 = json_encode(['forms' => array_values($arr2)]);
echo $str2;
This uses a foreach
loop to get unique forms and will create a new key fields
to hold the field_name_id
and field_caption
and also removes the pivot
key
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.