1

I am trying to create a dynamic navigation list that has a sublist for each of the items in the list

I have 1 array that contains 12 parent category values and is a straightforward 1 dimensional array.

I am looping through that with a foreach loop to make an unordered list

The problem I am having is that I have an array of subcategories that is a multidimensional array and I need to create a nested list for each of the subcategories that belong to the parent category.

<?php
//mysql query to get the parent categories  
$query  = "SELECT `parent` FROM `categories` GROUP BY `parent`";
$result = mysql_query($query);

while ($row = mysql_fetch_assoc($result)) {
    $cat[] = $row['parent']; //define the parent categories as a variable
}?>

<div id="navigation">
    <ul>
        <li><a href="http://localhost/softwarereviews.com">Home</a></li>
        <?php
        //loop through the parent categories
        foreach ($cat as $parent) {

            //another query to get the child categories that belong to each parent category
            $query = "SELECT * FROM `categories` WHERE `parent` = '$parent'";
            $result = mysql_query($query)
                or die(mysql_error());

            while ($row = mysql_fetch_assoc($result)) {
                //need 2 results so create a multi - dimensional array 
                $children[] = array($row['name'] => $row['cat_label']);

            }?>
            <li><?php echo $parent; ?></li>
            <ul>
                <?php foreach ($children as $key => $value) { ?>

                <?php foreach ($value as $key => $value) { ?>

                    <li><a href="<?php echo $value;?>"><?php echo $key;?></a><li>

                <?php }
            }?>
            </ul>
            <?php }?>
    </ul>
</div>

What happens at the moment is that the sub list of each category keeps appending the previous lists results, making the each sub list results bigger and bigger.

1
  • Your should not use $key => $value in your second for each! It's extremely confusing and prone to errors! At least name them such as $key2 => $value2 Commented Sep 8, 2011 at 17:32

2 Answers 2

3

initialize $children inside the foreach loop

foreach ($cat as $parent) { 
    $children = array();
    ...
Sign up to request clarification or add additional context in comments.

Comments

0

if you have a simple array

foreach($rows as $row){
    $row[0];
    $row['myKey'];
}

and if you have multidimensionnal array but this array can be with a unique row, do this

// foreach((condition)? true:false as child){ ... }
foreach((is_array($rows[0]))? $rows : array('0'=>$rows) as $row){
    $row[0];
    $row['myKey'];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.