1

Problem: I want to add the values of Array2 one-after-another to a multidimensional array (array1).

Array 1:

Array
(
    [0] => Array
        (
            [date] => 2020-01-01
            [itemsSold] => 25.00000000
        )

    [1] => Array
        (
            [date] => 2020-01-02 
            [itemsSold] => 50.00000000
        )

    [2] => Array
        (
            [date] => 2020-01-03 
            [itemsSold] => 25.00000000
        )
)

Array2:

Array
(
    [0] => 10
    [1] => 15
    [2] => 25
)

Goal:

Array
(
    [0] => Array
        (
            [date] => 2020-01-01
            [itemsSold] => 25.00000000
            [0] => 10
        )

    [1] => Array
        (
            [date] => 2020-01-02 
            [itemsSold] => 50.00000000
            [0] => 15
        )

    [2] => Array
        (
            [date] => 2020-01-03 
            [itemsSold] => 25.00000000
            [0] => 25
        )
)

I am just learning programming since january 2021 so my best solution I got was this:

foreach ($array1 as $main => $value) {
   foreach ($array2 as $sec => $entry) {
      $array1[$main][] = $array2[$sec];
   }
}
print_r($array1);

Output:

Array
(
    [0] => Array
        (
            [date] => 2020-01-01
            [itemsSold] => 25.00000000
            [0] => 10
            [1] => 15
            [2] => 25
        )

    [1] => Array
        (
            [date] => 2020-01-02 
            [itemsSold] => 50.00000000
            [0] => 10
            [1] => 15
            [2] => 25
        )

    [2] => Array
        (
            [date] => 2020-01-03 
            [itemsSold] => 25.00000000
            [0] => 10
            [1] => 15
            [2] => 25
        )
)

What am I doing wrong in my loop?? How can I get the values of array2 one-by-one into array1??

Thanks for any help ;)

Dorbn
  • 277
  • 4
  • 11

1 Answers1

1

The issue with your code is that you have nested a loop within another when you do not need to. Instead, use the loop format foreach ($array1 as $key => $value) so you can capture its index in $key, then use that as an index to $array2.

foreach ($array1 as $key => $value) {
  // Append from $array2 by its index $key
  // Using [] will append at index [0]
  // You can modify $array1 inside the loop if you 
  // target it by $key. Notice that we are not using
  // $value at all in this loop - only the $key matters.
  $array1[$key][] = $array2[$key]; 
}
print_r($array1);

foreach also allows you to modify the value directly if you use a & reference. This is a little bit shorter:

foreach ($array1 as $key => &$value) {
  // Looping over references to $array1 sub-arrays
  // means that $value can be modified directly
  $value[] = $array2[$key];
}
print_r($array1);

Iteration by reference is described in the PHP foreach manual

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390