Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP按同一数组中的值合并_Php - Fatal编程技术网

PHP按同一数组中的值合并

PHP按同一数组中的值合并,php,Php,我用PHP编写了这个数组 $arr = [ [ 'sections' => [1], 'id' => 1 ], [ 'sections' => [2], 'id' => 1 ], [ 'sections' => [3], 'id' => NULL ], [ 'sections' => [4], 'id' => 4 ], [ 'sections' => [5], 'id' => 4 ], [

我用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个以上的元素,您也可以选择排序方式……

这还不清楚。也许不同的键名会有帮助?方括号是从哪里来的。这是数组的完整wrogn格式@安东尼德·安德里亚:你试过了吗?PHP5.4。这是对数组的速记。关键名称在这里显示。@Abracadver,不知道这对5.4有效…每天学习一些东西!