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

时间:2015-01-01 18:22:59

标签: php mysql arrays

使用下面的代码,我会获得该类别中产品类别和名称的ID。类别ID被回显,在其下面,select显示该类别的产品名称。 现在它看起来像这样:

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

但我需要它在选项值产品ID中显示类别名称。 像这样:

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

我如何在下面的代码中实现这一目标?

    $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 个答案:

答案 0 :(得分:0)

让您的$categories数组成为二维:

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));
    }
}

然后你可以使用嵌套循环显示它:

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/>';
}