如何检索与数组中的查询关联的其他值? [重复]

This question already has an answer here:

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!!

</div>

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!