0

I have two arrays. The first array has a list of multidimensional arrays. The second array is similar, it also has a list of multidimensional arrays. The first array key has a list of description and the second array key has a list of amount. I need to combine both arrays and get the result shown in the below code. Somebody, please help me. See the below code for reference.

  • Array - 1
Array
(
    [0] => Array
        (
            [description] => Amul
        )

    [1] => Array
        (
            [description] => Kesar
        )

    [2] => Array
        (
            [description] => Flavour
        )

)
  • Array - 2
Array
(
    [0] => Array
        (
            [amount] => 100
        )

    [1] => Array
        (
            [amount] => 200
        )

    [2] => Array
        (
            [amount] => 300
        )

)
  • My result should be like the below.
Array
(
    [0] => Array
        (
            [description] => Amul
            [amount] => 100
        )

    [1] => Array
        (
            [description] => Kesar
            [amount] => 200
        )

    [2] => Array
        (
            [description] => Flavour
            [amount] => 3
        )

)
Ashish
  • 617
  • 5
  • 17

4 Answers4

2

you can do it "laravel way" with collection's zip method

  $result = collect($array1)->zip(collect($array2));

or already answered here (credits to @habnabit)

  $result = array_map(null, $a, $b, $c, ...);
Ol D. Castor
  • 360
  • 2
  • 8
2

For associative arrays with non-numeric keys you can use the php built in function array_merge_recursive. Something like this:

$arr = array
(
  'a'=>array
    (
      'description' => 'Amul'
    ),
  'b'=>array
    (
      'description' => 'Kesar'
    ),
  'c'=>array
    (
      'description' => 'Flavour'
    )
);

$arr2 = array
(
  'a'=>array
    (
      'amount' => '100'
    ),
  'b'=>array
    (
      'amount' => '200'
    ),
  'c'=>array
    (
      'amount' => '300'
    )
);

var_dump(array_merge_recursive($arr, $arr2));

FIDDLE LINK

If it is numeric keys, you have to use manual merging like in the other answers.

nazim
  • 1,386
  • 16
  • 25
1

This is achievable with a simple loop.

$arr = [['bla' => 1], ['bla' => 3]];
$arr2 = [['blu' => 2], ['blu' => 4]];

$newArr = [];

foreach ($arr as $key => $value) {
    $newArr[] = $value + $arr2[$key];
}

var_dump($newArr);

Note that this will only work if you the indexes of the input arrays align with each other.

Output:

array(2) {
  [0]=>
  array(2) {
    ["bla"]=>
    int(1)
    ["blu"]=>
    int(2)
  }
  [1]=>
  array(2) {
    ["bla"]=>
    int(3)
    ["blu"]=>
    int(4)
  }
}

Example: https://3v4l.org/WJhAR

ArSeN
  • 4,645
  • 3
  • 18
  • 26
1

You can simply do this by a loop:

$result = [];
for ($i = 0; $i < count($arr1); $i++) {
    $result[] = array_merge($arr1[$i], $arr2[$i]);
}
WebPajooh
  • 98
  • 6