使用foreach循环的PHP array_merge_recursive

时间:2019-07-09 13:26:31

标签: php arrays loops foreach array-merge

我想将几个数组合并为一个新数组,但是将它们按相同的键值分组

当我使用此循环

foreach($mrh as $group){
    print_r($group);
};

输出是

Array (
    [2] => 4
)
Array (
    [2] => 5
)
Array (
    [3] => 7
)
Array (
    [3] => 8
)
Array (
    [3] => 10
)

我想要的输出是

array (
    [2] => array(
        [0] => 4,
        [1] => 5
    ),
    [3] => array(
        [0] => 7,
        [1] => 8,
        [2] => 10,
    )
)

array_merge_recursive()可能有用,但我无法通过foreach循环来解决

4 个答案:

答案 0 :(得分:1)

简单地循环数组,并使用内部循环处理内部元素。然后根据它们的键将它们分配到结果数组中。

$result = [];
foreach ($mrh as $group) {
    foreach ($group as $key=>$value) {
        // Declare the array if it does not exist, to avoid notices
        if (!isset($result[$key]))
            $result[$key] = [];

        // Append the value
        $result[$key][] = $value;
    }
}

答案 1 :(得分:1)

如果内部数组的大小始终为 ,则可以将array-key-first用作:

foreach($mrh as $e) {
    $k = array_key_first($e);
    $res[$k][] = $e[$k];
}

实时示例:3v4l

答案 2 :(得分:0)

$mrh = [ [2=>4], [2=>5], [3=>7], [3=>8], [3=>10] ];
$newArray = [];

foreach($mrh as $group){ // loop over groups
  foreach($group as $key => $value) { // “loop over” group, to get access to key and value
    $newArray[$key][] = $value; // add value as a new element in the sub-array accessed by $key
  }
}

答案 3 :(得分:0)

使用foreach

 $a = [
[2 => 4],
[2 => 5],
[3 => 7],
[3 => 8],
[3 => 10]
];
$r = [];
foreach($a as $k => $v){
  $_value = end($v);
  $r[key($v)][] = $_value;
}
echo '<pre>';
print_r($r);