How to use ForEach in a multidimensional array in PHP
I would like to know how to run the whole array only with ForEach:
$Marcas = array(array('Fiat', 'Volkswagen', 'Audi'),array('Yamaha', 'Suzuki', 'Honda'),array('Samsung', 'Motorola', 'Apple'));
0
1 answers
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 one foreach
. You can do this if you get an array where it matches the junction of all sub-arrays.
For this you can use call_user_func_array
passing as first parameter "array_merge"
and as second to the mark array, and then just iterate normally:
$marcas = call_user_func_array("array_merge", $Marcas);
foreach ($marcas as $marca){
//código aqui
}
Can even do in a row śo if want:
foreach (call_user_func_array("array_merge", $Marcas) as $marca){
//código aqui
}
1
Author: Isac, 2018-06-07 21:42:57