简体   繁体   English

PHP array_merge_recursive使用foreach循环

[英]PHP array_merge_recursive using foreach loop

I want to merge a few array into a new array, but group them by the same key value 我想将几个数组合并为一个新数组,但将它们按相同的键值分组

When I use this loop 当我使用这个循环

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

Out put is 输出是

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

My desired output is 我想要的输出是

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

array_merge_recursive() may be useful, but i cant solve it with an foreach loop array_merge_recursive()可能有用,但是我无法通过foreach循环解决它

Simply loop the array, and with an inner loop, process the inner elements. 简单地循环数组,并使用内部循环处理内部元素。 Then assign them into the resulting array based on their key. 然后根据它们的键将它们分配到结果数组中。

$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;
    }
}

If your inner array is always on size 1 you can use array-key-first as: 如果内部数组的大小始终为1,则可以使用array-key-first作为:

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

Live example: 3v4l 直播示例: 3v4l

$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
  }
}

using foreach 使用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);

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

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