PHP按同一数组中的值合并

时间:2015-02-06 16:19:06

标签: 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 ]
];

我想合并一下' id'得到像

这样的东西
$arr = [
    [ 'sections' => [1, 2], 'id' => 1 ],
    [ 'sections' => [3], 'id' => NULL ],
    [ 'sections' => [4, 5, 6], 'id' => 4 ]
];

只是努力让我的头围绕这一个。任何想法

1 个答案:

答案 0 :(得分:3)

我已经创建了这个可能适合您的快速功能

<?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个元素,你也可以选择要排序的内容......