0

I'm trying to loop through this array to output side by side for every iteration.

$cars = [
    'BMW' => [
        'Year' => '2020',
        'Body' => 'Sedan',
        'Mileage' => '100'
    ],
    'Ford' => [
        'Year' => '2019',
        'Body' => 'SUV',
        'Mileage' => '500'
    ]
];

$count = count(reset($cars));
for($i=0; $i<$count; $i++) {
    foreach($cars as $key => $value) {
        echo $cars[$key][$i]. '<br>';
    }
}

My expected result for every iteration.

2020,2019
Sedan,SUV
100,500

I have searched through some links, but none is specific to a multidimensional array.

Two arrays in foreach loop How can I loop through two arrays at once?

KhorneHoly
  • 4,666
  • 6
  • 43
  • 75
ForALLs
  • 27
  • 5

2 Answers2

0

The other question you point to is about having separate arrays of data, which you could sort of emulate by splitting the main array into parts.

This solution assumes that all of the keys for the values you want are in the first item (as in your example, they all have the 3 values) and loops over the first array element and uses array_column() to extract all of the values from all of the main array elements for that key. Then implode() these values to put them as a CSV list...

foreach ( $cars[array_keys($cars)[0]] as $key => $value)    {
    echo implode(",", array_column($cars, $key)).PHP_EOL;
}

which with your test data gives...

2020,2019
Sedan,SUV
100,500
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
0

You can simply do it by storing your desired array values in another array and then implode them or make them work by your need. Take a look at the following code..

$cars = [
        'BMW' => [
            'Year' => '2020',
            'Body' => 'Sedan',
            'Mileage' => '100'
        ],

        'Ford' => [
            'Year' => '2019',
            'Body' => 'SUV',
            'Mileage' => '500'
        ],

    ];

    $year = [];
    $body = [];
    $milage = [];

foreach( $cars as  $key => $car ){
  if( $car['Year'] ){
      $year[] = $car['Year'];
  }
  if( $car['Body'] ){
      $body[] = $car['Body'];
  }
  if( $car['Mileage'] ){
      $milage[] = $car['Mileage'];
  }
}

var_dump(implode( ',', $year));
var_dump(implode( ',', $body));
var_dump(implode( ',', $milage));

will give you output:

string(9) "2020,2019" string(9) "Sedan,SUV" string(7) "100,500"
SOS9GS
  • 362
  • 1
  • 7