I have 2 arrays with me

First array

Array ( [2019-04-29] => Array ( [0] => 366 [1] => 82 [2] => 44 ) [2019-04-30] => Array ( [0] => 330 [1] => 115 [2] => 55 ) ) 

Second array

Array ( [0] => 492 [1] => 500 ) 

Need to merge these arrays with output like this.

Array ( [0] => Array ( [0] => 492 [1] => 366 [2] => 82 [3] => 44 ) [1] => Array ( [0] => 500 [1] => 330 [2] => 115 [3] => 55 ) ) 

Please help.

3 Answers

0
Rakesh Kumar Jakhar On Best Solutions

You can use array_walk and array_merge

$arr1 = Array ( 
        '2019-04-29' => Array (
                 '0' => 366, 
                 '1' => 82, 
                 '2' => 44 
        ) ,
        '2019-04-30' => Array ( 
                '0' => 330,
                '1' => 115, 
                '2' => 55 
        )
);
$arr2 = Array ( '0' => 492 ,'1' => 500 ) ;
$index = 0;
$res=[];
array_walk($arr1, function($v,$k) use (&$res,$arr2,&$index){
  $res[] = array_merge(array($arr2[$index]),$v);
  $index++;
});  
echo '<pre>';
print_r($res);

Result

Array
(
[0] => Array
    (
        [0] => 492
        [1] => 366
        [2] => 82
        [3] => 44
    )

[1] => Array
    (
        [0] => 500
        [1] => 330
        [2] => 115
        [3] => 55
    )

)
0
Nick On

You can do this with a foreach loop and array_merge, after using array_values to reindex $array1 to numeric indexes starting with 0.

$array1 = array_values($array1);
foreach ($array2 as $k => &$v) {
    $v = array_merge(array($v), $array1[$k]);
}
print_r($array2);

Output:

Array 
(
[0] => Array
    (
        [0] => 492
        [1] => 366
        [2] => 82
        [3] => 44
    )

[1] => Array
    (
        [0] => 500
        [1] => 330
        [2] => 115
        [3] => 55
    )
)

Demo on 3v4l.org

1
Rahul Meshram On

You can use array_walk and array_merge combination with traditional incrementer

array_walk($arr1, function (&$item, $key) use ($arr2,&$i) { // $i should change at memory address
    $item = array_merge($item, [$arr2[$i]]);
    $i++;
});

Output

Array
(
    [2019-04-29] => Array
        (
            [0] => 366
            [1] => 82
            [2] => 44
            [3] => 492
        )

    [2019-04-30] => Array
        (
            [0] => 330
            [1] => 115
            [2] => 55
            [3] => 500
        )

)

Demo.