0

The below code works for me to get all subcategory of a category but I also want to get the other fields associated with it in the foreach loop like if the subcategory is a Product like Smartphone then get its price as well.

How to get other values as well and show side by side in the foreach loop?

$query=mysql_query("SELECT * FROM thing WHERE tol_id='$bid' ORDER BY categoryname, name"); 
$categories = [];
if(mysql_num_rows($query) > 0){
    while($row=mysql_fetch_array($query)) {
        $categories[$row['categoryname']][] = $row['name'];
        $itsprice = $row['price'];
    }
}
if(!empty($categories)) {
    foreach($categories as $categoryName => $subCategories) {
        echo "<div class='stuff'>
                <p>".$categoryName."</p>
                <div id='rowstuff'>";
                if(!empty($subCategories)) {
                    foreach($subCategories as $subCategory) {
                        echo "<div id='name'>".$subCategory."</div>
                              <div id='price'>".$itsprice."</div>";
                    }
                }
        echo "</div></div>";
    }
}

The above code shows the price of the last subcategory and displays same for all of them!!

Abhi
  • 65
  • 10
  • does your query return values you need? `$categories[$row['categoryname']][] = $row` and then use something like this `$subCategory['name']` or `$subCategory['price']` – Viktar Pryshchepa Jul 19 '19 at 14:00
  • It does return what I need, but I want to get the other values along with what I get from the foreach loop! – Abhi Jul 19 '19 at 14:03

1 Answers1

0

Look add your code here:

while($row=mysql_fetch_array($query)) {
    $categories[$row['categoryname']][] = $row['name'];
    $itsprice = $row['price'];
}

Notice you add element to the $categories array but override each time the $itsprice var.

You should add that the the same array to extract later.

Consider the following change:

while($row=mysql_fetch_array($query)) {
    $categories[$row['categoryname']][] = ["name" => $row['name'], "price" => $row['price']];;
}

And later do:

foreach($subCategories as $subCategory) {
    echo "<div id='name'>" . $subCategory["name"] . "</div>
          <div id='price'>" . $subCategory["price"] . "</div>";
}

Hope this helps!

dWinder
  • 11,597
  • 3
  • 24
  • 39