PHP按同一数组中的值合并


PHP Merge by values in same array

所以我在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 ]
];

我想合并"id"并获得类似的东西

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

我只是很难理解这一点。任何想法

我创建了这个快速函数,它可能适用于

<?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));
?>

希望它能适用于2个以上的元素,您也可以选择排序内容。。。。