I want to make a loop to display each category and all sub-categories. I have this array:
$Allcategories = array(
array(
array("Category 1", 'category1'),
array("Sub 1", 'sub1'),
array("Sub 2", 'sub2'),
array("Sub 3", 'sub3')
),
array(
array("Category 2", 'category2'),
array("Sub 1", 'sub1'),
array("Sub 2", 'sub2'),
array("Sub 3", 'sub3')
)
);
I already made a 3-nest-for loop that works but I would like to simplify it with a foreach
. Here is my loop:for
foreach ($Allcategories as $val_1)
{
echo "<a href='index.php?category=", $val_1[0][1], "'>", $val_1[0][0], "</a>";
foreach ($val_1 as $val_2)
{
foreach ($val_2 as $val_3)
{
printf('<li><a href="index.php?category=%1$s">%1$s</a><br />', $val_3);
}
}
}
The problem is I'm getting this result:
Category 1
-Category 1
-category1
-Sub 1
-sub1
-Sub 2
-sub2
The inner loops shouldn't iterate over $Allcategories
, but rather, over the values from the outer loops:
foreach ($Allcategories as $layerNum => $layer) {
...
foreach ($layer as $rowNum => $row) {
...
foreach ($row as $colNum => $category) {
Although you should write it as ruakh has shown, it might be useful to know that the problem with your code is that you're forgetting to reference $key3
. It should be:
echo "<li><a href='index.php?category=".$Allcategories[$key1][$key2][$key3]
[1]."'>".$Allcategories[$key1][$key2][$key3][0]."</a><br />";
Edit: Or better yet, the whole thing:
foreach ($Allcategories as $val_1)
{
echo "<a href='index.php?category=" . $val_1[0][1] . "'>" . $val_1[0][0] . "</a>";
foreach ($val_1 as $val_2)
{
foreach ($val_2 as $val_3)
{
echo "<li><a href='index.php?category=" . $val_3[1] . "'>" . $val_3[0] . "</a><b></li>";
}
}
}
I've also taken the liberty or removing the <br />
and instead closed the <li>
as I believe that's what you want?