"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"
}
}
]
我想将表单对象分组为同名/ id。
我想要的......
"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"
}]
}
]
我搜索了所以并用Google搜索,但我找不到任何方法来解决我的问题。有类似问题的答案。
我做了foreach循环但我认为可能有一个方法在PHP中。
而且,如果我在json中有超过一百个对象,foreach可能会很慢。
感谢您的建议。
答案 0 :(得分:1)
尝试以下方法:
$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;
这会使用foreach
循环来获取唯一表单,并会创建一个新密钥fields
来保存field_name_id
和field_caption
并删除pivot
键