[英]How to combine an array with the same index
我有如下數組
[{"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]}]
有什么可能的方法來合並相同索引的值?
是的,可以解碼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”:[7,8]}]
<?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);
這是另一個選擇:
$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]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.