0

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

0

4 Answers 4

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

If your inner array is always on size 1 you can use array-key-first as:

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

Live example: 3v4l

1 Comment

Neat way of going about it, I like it!
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
  }
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.