我有一个数组如下
[{"2":[2]},{"9":[4,10,11,12,13,14,15,16,17,19,20,21,22,23,24,25,26,27,28,30,32,33,34,36,41]},{"2":[5,6,9]},{"7":[7,8]},{"9":[3]}]
有没有可能的方法来组合同一个索引的值?
答案 0 :(得分:2)
是的,可以解码json字符串并使用array_reduce:
$arr = json_decode('[{"2":[2]},{"9":[4,10,11,12,13,14,15,16,17,19,20,21,22,23,24,25,26,27,28,30,32,33,34,36,41]},{"2":[5,6,9]},{"7":[7,8]},{"9":[3]}]');
$arr = array_reduce($arr, function ($carry, $item) {
$key = key($item);
if (isset($carry[$key])) {
$carry[$key]->$key = array_merge($carry[$key]->$key, $item->$key);
} else {
$carry[$key] = $item;
}
return $carry;
});
echo json_encode(array_values($arr));
结果是:
[{" 2":[2,5,6,9]},{" 9":[4,10,11,12,13,14,15, 16,17,19,20,21,22,23,24,25,26,27,28,30,32,33,34,36,41,3]},{" 7&#34 ;: [7,8]}]
答案 1 :(得分:0)
<?php
$json = '[{"2":[2]},{"9":[4,10,11,12,13,14,15,16,17,19,20,21,22,23,24,25,26,27,28,30,32,33,34,36,41]},{"2":[5,6,9]},{"7":[7,8]},{"9":[3]}]';
$multi_array = json_decode($json, true);
$result = [];
foreach($multi_array as $arr)
{
foreach($arr as $k => $v)
{
$temp = isset($result[$k]) ? $result[$k] : [];
$result[$k] = array_merge($temp, $v);
}
}
print_r($result);
答案 2 :(得分:0)
这是另一种选择:
$old = json_decode('[{"2":[2]},{"9":[4,10,11,12,13,14,15,16,17,19,20,21,22,23,24,25,26,27,28,30,32,33,34,36,41]},{"2":[5,6,9]},{"7":[7,8]},{"9":[3]}]', true);
$new = [];
array_map(function ($arr) use (&$new) {
$key = key($arr);
$new[$key] = array_merge(current($arr), !empty($new[$key]) ? $new[$key] : []);
}, $old);
echo json_encode($new);
输出:
{"2":[5,6,9,2],"9":[3,4,10,11,12,13,14,15,16,17,19,20,21,22,23,24,25,26,27,28,30,32,33,34,36,41],"7":[7,8]}