0

I would like to collate data from multiple different data sources into one numeric array using foreach loops, however I am having some trouble building my array in the expected format. I would like to keep the key numeric.

For example, if I had two data sources: $fruit_data and $flavor_data and my code was:

foreach($fruit_data as $fruit){
    $fruits[]['name'] = $fruit['name'];
}

foreach($flavor_data as $flavor){
    $fruits[]['flavor'] = $flavor['taste'];
}

The data is added to the array with separate numeric keys, like this:

Array
(
    [0] => Array
        (
            [name] => Example Name 1 
        )

    [1] => Array
        (
            [flavor] => Example Flavor 1
        )
    [2] => Array
        (
            [name] => Example Name 2 
        )

    [3] => Array
        (
            [flavor] => Example Flavor 2
        )
)

However, my desired output is to display the data under the same numeric key, like this:

Array
(
    [0] => Array
        (
            [name] => Example Name 1
            [flavor] => Example Flavor 1
        )
    [1] => Array
        (
            [name] => Example Name 2
            [flavor] => Example Flavor 2
        )
)

Could somebody please explain where I am going wrong, and if possible, link me to a resource that explains how to overcome this issue? It may be that I have a fundamental misunderstanding of multidimensional arrays, but I cannot seem to find any references to this issue.

Any help is much appreciated.

Syn
  • 331
  • 1
  • 13
  • Use the index and only one `foreach`. `foreach($fruit_data as $key => $fruit){ $fruits[] = array('name' => $fruit['name'], 'flavor' => $flavor_data[$key]['flavor']);` – user3783243 Aug 22 '20 at 18:42
  • When you say one `foreach`, would you be able to show me an example of how to do this? I am not sure how to loop through two data arrays in one foreach. Thank you! – Syn Aug 22 '20 at 18:43
  • 1
    I've updated comment, give that a try... that's also a rough idea, might have a typo in it. – user3783243 Aug 22 '20 at 18:45
  • Thank you, I will take a look into that and try to figure it out! – Syn Aug 22 '20 at 18:47

1 Answers1

0
foreach($fruit_data as $index => $fruit){
    $fruits[] = [
        'name' => $fruit['name'],
        'flavor' => $flavor_data[$index]['taste']
    ];
}

Same as

foreach($fruit_data as $index => $fruit){
    $fruits[] = [
        'name' => $fruit_data[$index]['taste'],
        'flavor' => $flavor_data[$index]['taste']
    ];
}
Prince Dorcis
  • 955
  • 7
  • 7