1

I have an app that users choose items and then it fills a table that has two columns in it: Category and Items. Its something like this:

Category  | Items 
-----------------
PET       | Dog Food
HEALTH    | Tooth Brush
PET       | Cat Food
COLD FOOD | Steak
COLD FOOD | Eggs

In my select statement I order the data by Category then by Items and I am using a WHILE loop to drop the data into an array.

while($listItems = mysql_fetch_array($results))
{
    $myArray[] = array("category" => $listItems["Category"],
                       "item"     => $listItems["Name"]);
}

When I do a print_r($myArray); I get something like this:

Array ( [0] => Array ( [category] => Cold Food [item] => Steak )
        [1] => Array ( [category] => Food      [item] => Eggs )
        [2] => Array ( [category] => Health    [item] => Tooth Brush )
        [3] => Array ( [category] => Pet       [item] => Cat Food )
        [4] => Array ( [category] => Pet       [item] => Dog Food ) )

What I am wanting to do is output the data into a nested list something like this.

  • Cold Food
    • Steak
    • Eggs
  • Health
    • Tooth Brush
  • Pet
    • Cat Food
    • Dog Food

Any help is welcomed! Thanks!

1

4 Answers 4

4

Try this:

while($listItems = mysql_fetch_array($results))
{
    $cat  = $listItems['Category'];
    $name = $listItems['Name'];

    if(!isset($myArray[$cat]))
      $myArray[$cat] = array();

    $myArray[$cat][] = $name;
}

Then, to output it you'd do this:

$buffer = '<ul>';
foreach($myArray as $cat => $items) {
   $buffer .= "<li>$cat</li><li><ul>";
   foreach($items as $item) {
      $buffer .= "<li>$item</li>";
   }
   $buffer .= '</ul></li>';
}
$buffer .= '</ul>';
echo $buffer;
Sign up to request clarification or add additional context in comments.

1 Comment

Jacob you rock. I been scratching my head on this for weeks and you nailed it in 13mins. The only change I had to make was on the second "$buffer". I changed it from $buffer .='<li><ul>'; to $buffer .='<li>'.$cat.'</li><ul>';
1

Give this a try. The idea is to reorganize your data into a more convenient form, namely to have the items indexed by category.

Code

<?php
    $items = array
    (
        array('category' => 'Cold Food', 'item' => 'Steak'),
        array('category' => 'Food', 'item' => 'Eggs'),
        array('category' => 'Health', 'item' => 'Tooth Brush'),
        array('category' => 'Pet', 'item' => 'Cat Food'),
        array('category' => 'Pet', 'item' => 'Dog Food'),
    );

    // Group the items by category.
    $itemsByCategory = array();

    foreach ($items as $item)
    {
        $category = $item['category'];
        $name     = $item['item'];

        if (!array_key_exists($category, $itemsByCategory))
            $itemsByCategory[$category] = array();

        $itemsByCategory[$category][] = $name;
    }

    // Output nested lists for the items.
?>  <ul>
<?php foreach ($itemsByCategory as $category => $items)
      {
?>        <li><?php echo htmlspecialchars($category); ?>

              <ul>
<?php           foreach ($items as $item)
                {
?>                  <li><?php echo htmlspecialchars($item); ?></li>
<?php           }
?>            </ul>
          </li>
<?php }
?>  </ul>

Output

  • Cold Food
    • Steak
  • Food
    • Eggs
  • Health
    • Tooth Brush
  • Pet
    • Cat Food
    • Dog Food

2 Comments

This would work, but don't you think it'd be DRYer to have a nested array?
doesn't asort($items) save you from creating an entire new array?
1
<?
//establish $vlink before
$query = 'select distinct (category) from list';
$result = mysql_query($query,$vlink);

while($row = mysql_fetch_array($results))
{
    $query1 = "select items from list where category = ".$row[0];
    $result1 = mysql_query($query1,$vlink);

    echo '<h1>'.$row[0].'</h1>';
    while($row1 = mysql_fetch_array($result1))
    {
        echo '<h2>'.$row1[0].'</h2>';
    }
}
?>

Comments

0

Try with this:

while($listItems = mysql_fetch_array($results)) 
{
     $myArray[$listItems["Category"]][] = $listItems["Name"] 
}

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.