我以 JSON 格式获取数据,并希望通过将我收到的对象放入与其 id 对应的数组中来对我收到的对象进行排序。 我得到的数据有这样的格式:
{
"data": {
"members": [
{
"groupId": "1",
"name": "a"
},
{
"groupId": "2",
"name": "b"
},
{
"groupId": "2",
"name": "c"
},
{
"groupId": "1",
"name": "d"
}
]
}
}
所以我从成员数组中获取对象,并尝试将它们中的每一个放入具有匹配 groupId 的数组中,它应该如下所示:
{
"1": [
{
"groupId": "1",
"name": "a"
},
{
"groupId": "1",
"name": "d"
}
],
"2": [
{
"groupId": "2",
"name": "b"
},
{
"groupId": "2",
"name": "c"
}
]
}
我想通过使用 foreach 循环并将对象添加到它们的数组中来实现这一点,如下所示:
$json_data = file_get_contents('getfromFile.json');
$json_decoded = json_decode($json_data, true);
foreach($json_decoded['data']['members'] as $item) {
$json_sorted[$item['groupId']] = $item;
}
但是像这样,数组中只添加一个对象。如何将多个对象正确添加到特定数组?
试试我的代码。
如果您应该将最后一个结果打印为 json,您可以使用 json_encode,或者如果您需要使用数组,只需使用数组$res
数组作为最终结果
<?php
$json = '{
"data": {
"members": [
{
"groupId": "1",
"name": "a"
},
{
"groupId": "2",
"name": "b"
}
]
}
}';
$obj = json_decode($json,true);
// Final result
$res = [];
foreach($obj['data']['members'] as $el){
// Adding element to group array
$res[$el['groupId']][] = $el;
}
echo json_encode($res);
//var_dump($res);
这可以解决您的问题。如果您有超过 1 件商品,则返回收藏或仅收集一件商品:
$json_data = file_get_contents('getfromFile.json');
$json_decoded = json_decode($json_data, true);
$jsonDecodedCollection = [];
foreach($json_decoded['data']['members'] as $item) {
if (isset($jsonDecodedCollection[$item['groupId']])) {
$jsonDecodedCollection[$item['groupId']] = isset($jsonDecodedCollection[$item['groupId']][0]) ? array_push($jsonDecodedCollection[$item['groupId']], $item) : $jsonDecodedCollection[$item['groupId'] = array_merge([$jsonDecodedCollection[$item['groupId']], [$item]);
} else {
$jsonDecodedCollection[$item['groupId']] = $item;
}
}
var_dump($jsonDecodedCollection);