Add one array to a multidimensional array

I want to add the values โ€‹โ€‹of array b to array a:

$a = [[1, 2],[4, 5],[7, 8]];
$b = [3, 6, 9];

      

The result should be:

$result = [[1, 2, 3],[4, 5, 6],[7, 8, 9]];

      

I am trying this (and many other things) but don't get it.

foreach ($a as $el) {
    $i = 0; 
    $el[] = $b[$i];
    $i++;
}

      

+3


source to share


5 answers


This is not difficult.



<?php
$a = [[1, 2],[4, 5],[7, 8]];
$b = [3, 6, 9];
for($i = 0; $i < count($b);$i++) {
    array_push($a[$i],$b[$i]);
}
?>

      

+3


source


Here we use array_walk

to achieve the desired result. Hope this will be helpful.

Try this piece of code here



<?php
ini_set('display_errors', 1);
$a = [[1, 2],[4, 5],[7, 8]];
$b = [3, 6, 9];

array_walk($a,function(&$value,$key) use($b){
    array_push($value, $b[$key]);
});
print_r($a);

      

+5


source


It should be simple:

$a = [[1, 2],[4, 5],[7, 8]];          
$b = [3, 6, 9];
foreach($a as $key => &$arr){
    $arr[] = $b[$key];
}

      

+4


source


$a = [[1, 2],[4, 5],[7, 8]];
$b = [3, 6, 9];
$result = $a;
foreach ($a as $key => $val) {
    if(!empty($b[$key])) {
        array_push($result[$key], $b[$key]);
    }
}

var_export($result);

      

0


source


Here's a clever one-liner that nobody thought of:

Code: ( Demo )

$a = [[1, 2],[4, 5],[7, 8]];          
$b = [3, 6, 9];

var_export(array_map('array_merge',$a,array_chunk($b,1)));

      

Output:

array (
  0 => 
  array (
    0 => 1,
    1 => 2,
    2 => 3,
  ),
  1 => 
  array (
    0 => 4,
    1 => 5,
    2 => 6,
  ),
  2 => 
  array (
    0 => 7,
    1 => 8,
    2 => 9,
  ),
)

      

This approach breaks down $b

into the same structure as $a

, then just combine them together.

If your input arrays are relatively small, it is best to choose foreach()

. As your input array grows in size, I believe that you will find that my approach will have higher performance advantages over foreach()

(although I will be honest, I base this on other similar answers I have provided, and I actually haven't tested this case).

0


source







All Articles