So, I am still learning PHP, and I wanted to customize the arrays a bit in matter of structure, so they are not static. But I've came to a problem. I've managed to write out each array that has an array inside of it, but now I struggle in finding a way of writing out the ones that do not have an array inside of them, and not to get 0-s and 1-s instead of the actual name of the array elements.
I basically need some advice on how to make this work properly, I wouldn't mind if you could tell me a more efficient way of writing everything out and solving the problem at the same time.
<?php
$food = array(
'Healthy'=>array( 'Salad'=> array('Fruit Salad','Tropical Salad'),
'Vegetables'=>array('Carrot','Cucumber'),
'Pasta'),
'Unhealthy'=>array('Pizza','Ice Cream')
);
foreach ($food as $type=>$food_types) {
echo '<b>'.$type.'</b>'.'<br>';
if (is_array($food_types)) {
foreach($food_types as $type_names=>$fruits) {
if (isset($type_names) && !empty($type_names) && is_array($fruits)) {
echo $type_names.'<br>';
foreach ($fruits as $name_of_fruits) {
echo '<i>'.$name_of_fruits.'</i>'.'<br>';
}
}
}
} else {
echo $food_types;
}
}
?>
**UPDATE*** Thanks to celeriko's comment I found the problem, being newbie to PHP I didn't really knew that the type of "Healthy Food" that was not an array was actually the first index of the big "Healthy Food" array, as the other two were array and didn't count as actual indexes.
Here is the fixed code, thank you cerleriko once again!
<?php
$food = array(
'Healthy'=>array( 'Salad'=> array('Fruit Salad','Tropical Salad'),
'Vegetables'=>array('Carrot','Cucumber'),
'Pasta'),
'Unhealthy'=>array('Pizza','Ice Cream')
);
foreach ($food as $type=>$food_types) {
echo '<b>'.$type.'</b>'.'<br>';
if (is_array($food_types)) {
foreach($food_types as $type_names=>$fruits) {
if (isset($type_names) && !empty($type_names) && is_array($fruits)) {
echo $type_names.'<br>';
foreach ($fruits as $name_of_fruits) {
echo '<i>'.$name_of_fruits.'</i>'.'<br>';
}
} else {
echo $fruits.'<br>'; /* Here I had to enter this line and everything works fine! */
}
}
} else {
echo $food_types;
}
}
?>