duandaijian1583 2019-07-19 13:56
浏览 86
已采纳

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

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>
  • 写回答

1条回答 默认 最新

  • dongyong3554 2019-07-19 14:09
    关注

    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!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?