douman6679 2015-01-01 18:22
浏览 61
已采纳

从数组中的数据库中获取多行

With code below I get id of category and name of products in that category. Category id is echoed and under it select is shown with products names for that category. Now it looks like this:

<label>37</label> <!--category id-->
<select>
<option>product one</option>
<option>product two</option>
</select>

But I need it to show category name an in option value product id. Like this:

<label>category name</label>
<select>
<option value="1">product one</option>
<option value="2">product two</option>
</select>

How can I achieve that in code below?

    $categories = array();
    $sql= "
SELECT a.id
     , a.name
     , a.active
     , b.id product_id
     , b.name product_name
     , b.flag_active
     , c.product_id
     , c.group_id 
  FROM products_groupnames a 
  JOIN products_group c 
    ON a.id = c.group_id 
  JOIN products_name b 
    ON b.id = c.product_id
 WHERE a.active=1 
   AND b.flag_active = 1
";
    $result = $mysqli->query($sql);
    echo "<h4>Select products by groups</h4>";
    while($row = $result->fetch_assoc()) {
        $categories[$row['id']][] = $row['product_name'];
    }

    foreach($categories as $key => $category){
        echo '<label>'.$key.'</label><br/>';
        echo '<select>';
        foreach($category as $item){
            echo "<option>".$item."</option>";
        }
        echo "</select><br/>";
    }
  • 写回答

1条回答 默认 最新

  • dry0106 2015-01-01 18:28
    关注

    Make your $categories array 2-dimensional:

    while ($row = $result->fetch_assoc()) {
        $cat = $row['id'];
        if (isset($categories[$cat])) {
            $categories[$cat]['products'][] = $row;
        } else {
            $categories[$cat] = array('name' => $row['name'], products => array($row));
        }
    }
    

    Then you can display it using nested loops:

    foreach ($categories as $category) {
        echo '<label>'.$category['name'].'</label>';
        echo '<select>';
        foreach ($category['products'] as $prod) {
            echo '<option value="'.$prod['product_id'].'">'.$prod['product_name'].'</option>';
        }
        echo '</select><br/>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示