user866190
user866190

Reputation: 863

php how to loop through a multi dimensional array

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.

Upvotes: 1

Views: 1652

Answers (2)

pirs
pirs

Reputation: 2463

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'];
}

Upvotes: 0

Charlie
Charlie

Reputation: 1072

initialize $children inside the foreach loop

foreach ($cat as $parent) { 
    $children = array();
    ...

Upvotes: 3

Related Questions