Home > other >  Combined arrays
Combined arrays

Time:05-28

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
        )

)

CodePudding user response:

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

CodePudding user response:

You can simply do this by a loop:

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