我有一个包含对象的数组,如果类似的键已经存在,我想实现的是对对象进行分组。我的JSON输出看起来是
[
{
"id": 37,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "38"
},
{
"id": 38,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "40"
},
{
"id": 34,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "36"
},
{
"id": 26,
"slug": "green",
"stock": true,
"name": "Green",
"default": 0,
"sizes": "48"
}
我想要实现的是将类似的弹头分组,并将所有大小的数组组合成一个。因此,如下所示,
[
{
"slug": "red",
"name": "Red",
"sizes" : [{
"id": 37,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "38"
},
{
"id": 38,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "40"
},
{
"id": 34,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "36"
}]
}, {
"slug": "green",
"name": "Green",
"sizes": [{
"id": 26,
"slug": "green",
"stock": true,
"name": "Green",
"default": 0,
"sizes": "48"
}]
}
]
我不是PHP专家,所以整天试图弄清楚如何进行这种搜索,希望有人能熟练使用PHP可以帮助我。
答案 0 :(得分:3)
您可以先使用一个循环将结果按slug
分组,然后再使用另一个循环来获得所需的内容。让我们这样尝试吧-
<?php
$json = '[{"id":37,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"38"},{"id":38,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"40"},{"id":34,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"36"},{"id":26,"slug":"green","stock":true,"name":"Green","default":0,"sizes":"48"}]';
$array = json_decode($json,1);
$expected = [];
foreach($array as $v) {
$expected[$v['slug']][] = $v;
}
$expected_v2 = [];
foreach($expected as $k1=>$v1) {
array_push($expected_v2,['slug'=>$k1,'name'=>ucfirst($k1),'sizes'=>$v1]);
}
//print_r($expected_v2);
echo json_encode($expected_v2);
?>
输出:
[{"slug":"red","name":"Red","sizes":[{"id":37,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"38"},{"id":38,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"40"},{"id":34,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"36"}]},{"slug":"green","name":"Green","sizes":[{"id":26,"slug":"green","stock":true,"name":"Green","default":0,"sizes":"48"}]}]
答案 1 :(得分:1)
您可以使用`array_reduce实现此目的:
$json = '[{"id":37,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"38"},{"id":38,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"40"},{"id":34,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"36"},{"id":26,"slug":"green","stock":true,"name":"Green","default":0,"sizes":"48"}]';
$input = json_decode($json, true);
$output = array_reduce(array_reduce($input, function ($carry, $item) {
$carry[$item['slug']][] = $item;
return $carry;
}, []), function ($carry, $group) {
$carry[] = [
'slug' => $group[0]['slug'],
'name' => $group[0]['name'],
'sizes' => $group
];
return $carry;
}, []);