我有这样的数据json:
[
{
"created_at": "2019-02-17 15:08:11",
"description": "black,white",
"id": 1,
"name": "mamat",
"updated_at": "20169-02-17 15:08:11"
},
{
"created_at": "2019-02-17 15:08:31",
"description": "yellow,red,green",
"id": 2,
"name": "klomangan",
"updated_at": "2019-02-17 15:08:31"
}
]
但是,我想要这样的json,合并名称和描述。
{
"name": "mamat klomangan",
"description": "black,white,yellow,red,green"
}
注意:我正在使用Laravel / PHP和SQL
答案 0 :(得分:0)
假设您要使用相同的键合并两个json对象,请遵循以下功能:
$people = '[{"name":"John", "color":"green"},
{"name":"Mary", "color":"green"},
{"name":"Bob", "color":"red"}]';
$people_json = json_decode($people, True);
$merged_array = array();
foreach ($people_json as $person) {
if (isset($people_by_color[$person['color']])) {
$people_by_color[$person['color']]['name'] .= ', ' . $person['name'];
$people_by_color[$person['color']]['color'] .= ', ' . $person['color'];
} else {
$people_by_color[$person['color']] = $person;
}
}
$merged_array_final = array_values($people_by_color); // Turn into indexed array
print_r($merged_array_final);