简体   繁体   English

PHP通过同一数组中的值合并

[英]PHP Merge by values in same array

So I have this array in PHP. 所以我在PHP中有这个数组。

$arr = [
    [ 'sections' => [1], 'id' => 1 ],
    [ 'sections' => [2], 'id' => 1 ],
    [ 'sections' => [3], 'id' => NULL ],
    [ 'sections' => [4], 'id' => 4 ],
    [ 'sections' => [5], 'id' => 4 ],
    [ 'sections' => [6], 'id' => 4 ]
];

I want to merge on 'id' and get something like 我想合并'id'并得到类似

$arr = [
    [ 'sections' => [1, 2], 'id' => 1 ],
    [ 'sections' => [3], 'id' => NULL ],
    [ 'sections' => [4, 5, 6], 'id' => 4 ]
];

Just struggling to get my head around this one. 只是努力使我的脑袋绕过去。 Any Ideas 有任何想法吗

I've created this quick function that might work for you 我创建了此快速功能,可能对您有用

<?php 
// Your array
$arr = array(
        array( 'elem1' => 1, 'elem2' => 1 ),
        array( 'elem1' => 2, 'elem2' => 1 ),
        array( 'elem1' => 3, 'elem2' => NULL ),
        array( 'elem1' => 4, 'elem2' => 4 ),
        array( 'elem1' => 5, 'elem2' => 4 ),
        array( 'elem1' => 6, 'elem2' => 4 )
);
print_r($arr);

function mergeBy($arr, $elem2 = 'elem2') {
    $result = array();

    foreach ($arr as $item) {
        if (empty($result[$item[$elem2]])) {
            // for new items (elem2), just add it in with index of elem2's value to start
            $result[$item[$elem2]] = $item;
        } else {
            // for non-new items (elem2) merge any other values (elem1)
            foreach ($item as $key => $val) {
                if ($key != $elem2) {
                    // cast elem1's as arrays, just incase you were lazy like me in the declaration of the array
                    $result[$item[$elem2]][$key] = $result[$item[$elem2]][$key] = array_merge((array)$result[$item[$elem2]][$key],(array)$val);
                }
            }
        }
    }
    // strip out the keys so that you dont have the elem2's values all over the place
    return array_values($result);
}

print_r(mergeBy($arr));
?>

Hopefully it'll work for more than 2 elements, and you can choose what to sort on also.... 希望它可以用于2个以上的元素,并且您还可以选择要排序的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM