SQL连接2个表并遍历结果

我有这个SQL查询从2个表中获取数据,并根据匹配的ID加入他们。


SELECT   *

FROM     bar_items 

   LEFT JOIN bar_cats ON

         bar_cats.cat_id = bar_items.categories

ORDER BY bar_items.categories,

         bar_items.item_name ASC

这给我这个结果

http://img3.mukewang.com/60a759cd0001262810530183.jpg

我现在尝试将这些显示在类别中,并以类别名称作为每个类别的标题。


到目前为止,我在旧的Stack Overflow帖子的帮助下有此代码:这里


    $data = array(); 

foreach($results_lists as $row){

        $data[$row['cat_name']][$row['item_name']]['item_name'] = $row['item_name'];

        $data[$row['cat_name']][$row['item_price']]['item_price'] = $row['item_price'];

        $data[$row['cat_name']][$row['item_image']]['item_image'] = $row['item_image'];

    } foreach($data as $category => $events){


        echo $category.'<br>';


        foreach($events as $event){

            echo '    <> '.$event['item_name'].'<br>';

            echo '        <> '.$event['item_price'].'<br>';

            echo '        <> '.$event['item_image'].'<br>';

        }

但它没有按照我的需要运行,并且显示如下:(请注意空白的<>行,在列表的最下方,即使在查询中返回了某些价格,也不会显示某些价格)

我要去哪里错了?



临摹微笑
浏览 159回答 1
1回答

慕森卡

我认为您正在使生活变得比实际需要的更加复杂。通过结果集的简单传递应该能够产生您希望的输出。$last_cat = null;foreach($results_lists as $row){&nbsp; &nbsp; if ( $last_cat != $row['cat_name'] ) {&nbsp; &nbsp; &nbsp; &nbsp; echo $row['cat_name'] . '<br>';&nbsp; &nbsp; &nbsp; &nbsp; $last_cat = $row['cat_name'];&nbsp; &nbsp; }&nbsp; &nbsp; echo '&nbsp; &nbsp; <> '.$row['item_name'].'<br>';&nbsp; &nbsp; echo '&nbsp; &nbsp; &nbsp; &nbsp; <> '.$row['item_price'].'<br>';&nbsp; &nbsp; echo '&nbsp; &nbsp; &nbsp; &nbsp; <> '.$row['item_image'].'<br>';}&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP