How to use ForEach in a multidimensional array in PHP

0

I would like to know how to run the entire array with ForEach only:

$Marcas = array(array('Fiat', 'Volkswagen', 'Audi'),array('Yamaha', 'Suzuki', 'Honda'),array('Samsung', 'Motorola', 'Apple')); 
    
asked by anonymous 07.06.2018 / 23:13

1 answer

1

A multidimensional array would normally be traversed with a double foreach . In your case with:

foreach ($Marcas as $subMarcas){
    foreach ($subMarcas as $marca){
        //código aqui
    }
}

However I got the idea that I wanted to do something with only foreach . You can do this if you get an array that matches the merge of all sub-arrays.

For this you can use call_user_func_array passing as the first parameter "array_merge" and second as the array of tags, and then just iterate normally:

$marcas = call_user_func_array("array_merge", $Marcas);
foreach ($marcas as $marca){
    //código aqui
}

You can even do it on a line if you want:

foreach (call_user_func_array("array_merge", $Marcas) as $marca){
    //código aqui
}

See this last example in Ideone

    
07.06.2018 / 23:42