Reputation: 13
Ok, so I'm trying to get the hang of multidimensional arrays, I know what they are and what they do.
In the example below I have created (probably not the most efficient way) a Cars array
.
In this array I have two other variables that contain arrays, one for the model and one for the colour.
The result I'm looking for is to echo out all the models and colours for each car car.
For example
Bmw Red Saloon, Bmw Red Hatchback, Bmw Red Estate, Bmw Green Saloon, Bmw Green Hatchback etc etc.
So far in the following code I can get the make of the cars but then it echoes array array.
<?php
$colours = array("red","green","blue");
$models = array("hatchback","saloon","estate");
$cars= array(
array("Bmw",$colours,$models),
array("Volvo",$colours,$models),
array("VW",$colours,$models),
array("Mercedes",$colours,$models)
);
foreach ($cars as $innerArray){
foreach ($innerArray as $value) {
echo $value . '<br/>';
}
}
?>
I know the foreach statement is wrong but that's where I'm stuck. If you could help me out or even better explain the logic behind it, that would be awesome!
Upvotes: 1
Views: 153
Reputation: 117
I would not try to combine your array, that's what your loop is for. Keep it simple - colours array has colours, models has models, cars has cars. Then the variable names in your loops make more sense and it's easier to loop over. All you then have to do is loop over each one.
$colours = array("red","green","blue");
$models = array("hatchback","saloon","estate");
$cars = array("Bmw","Volvo","VW","Mercedes");
foreach($cars as $car)
{
foreach($colours as $colour)
{
foreach($models as $model)
{
echo $car.' '.$colour.' '.$model.'<br>';
}
}
}
Upvotes: 0
Reputation: 2406
Try this :
$r = count($cars);
for ($row = 0; $row < $r; $row++)
{
echo "<ul>";
for ($col = 0; $col < 3; $col++)
{
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
Upvotes: 0
Reputation: 32912
The other asnwers should work for you well, just to be complete, here is the array_walk_recursive code:
function walkFunction($value,$key) {
echo "$key: $value<br/>";
}
array_walk_recursive($cars,"walkFunction");
Upvotes: 1
Reputation: 5057
your $value sometimes is a string, and sometimes an array. Echo will not work for arrays. Try var_dump instead of echo.
foreach ($cars as $innerArray){
foreach ($innerArray as $value)
{var_dump($value);
}
}
Upvotes: 0
Reputation: 785098
Use any of the following available functions to dump out your top level array variable:
Upvotes: 3
Reputation: 243
In your array 'cars' there are strings and arrays, so when you echo the $value you are trying to echo an array 2/3 of the times.
If you just want to echo the stuff, I would suggest you to use
print_r()
Upvotes: 2