在列表中分组 - php

时间:2014-06-15 17:13:20

标签: php mysql list map

我有mysql结果,如下所示。我想制作基于商店的清单,我该怎么做PHP?

 SELECT shsv.shop_id, sv.shop, shsv.shop_product_id, shsv.shop_product, sum(shsv.cash) 
  FROM turerp_db.shop_has_sale_view shsv 
  left JOIN shop_view sv ON ( sv.shop_id = shsv.shop_id ) 
  group by shsv.shop_id, shsv.shop_product_id

ID SHOP P_ID产品价格
10 SHOP_1 14 PRODUCT_1 322

11 SHOP_2 3 PRODUCT_2 2000

11 SHOP_2 5 PRODUCT_3 55

SHOP_1

  • PRODUCT_1

SHOP_2

  • PRODUCT_2
  • PRODUCT_3

3 个答案:

答案 0 :(得分:0)

您可以使用PHP数组的关联性质:http://www.php.net/manual/en/language.types.array.php

$shops = [];
$shops['SHOP_1'][] = 'PRODUCT_1';
$shops['SHOP_2'][] = 'PRODUCT_2';
$shops['SHOP_2'][] = 'PRODUCT_3';

var_dump($shops)将打印:

array(2) {
  ["SHOP_1"]=>
  array(1) {
    [0]=>
    string(9) "PRODUCT_1"
  }
  ["SHOP_2"]=>
  array(2) {
    [0]=>
    string(9) "PRODUCT_2"
    [1]=>
    string(9) "PRODUCT_3"
  }
}

您还应该参考您的mysql驱动程序文档。它的某些方法可能会以类似的方式返回您的数据。

答案 1 :(得分:0)

试试这个

$sql = mysql_query("SELECT * FROM tablename ORDER BY SHOP P_ID ASC");//your query
$cat = ""; //initialize $cat variable 
while($row = mysql_fetch_assoc($sql)){ 
if($row['SHOP P_ID '] != $cat) echo "<h3>".$row['SHOP P_ID ']."</h3>\r\n"; 
echo "<p>".$row['PRODUCT']."</p>\r\n"; 
$cat = $row['SHOP P_ID']; 
} 

答案 2 :(得分:0)

我自己找到了解决方案,如果您有更好的解决方案,请与我们分享。

$query = $this -> db -> query('SELECT shsv.shop_id, sv.shop, shsv.shop_product_id, shsv.shop_product, sum(shsv.cash) AS cash_total FROM turerp_db.shop_has_sale_view shsv left JOIN shop_view sv ON ( sv.shop_id = shsv.shop_id )  group by shsv.shop_id, shsv.shop_product_id');
        $shops= $query -> result();
        $count = 0;
        echo '<table>';
        foreach ($shops as  $shop) {
            if($count == 0){
                echo '<thead><tr><th colspan="2">'.$shop->shop.'</th></tr></thead>';
                echo '<tbody>';
                echo '<tr><td>'.$shop->shop_product.'</td><td>'.$shop->cash_total.'</td></tr>';
                $shop_id = $shop -> shop_id;
            }
            else {
                    if($shop_id == $shop -> shop_id){
                        echo '<tr><td>'.$shop->shop_product.'</td><td>'.$shop->cash_total.'</td></tr>';
                    }
                    else {
                        echo '</tbody>';
                        echo '<thead><tr><th colspan="2">'.$shop->shop.'</th></tr></thead>';
                        echo '<tbody>';
                        echo '<tr><td>'.$shop->shop_product.'</td><td>'.$shop->cash_total.'</td></tr>';
                    }
                    $shop_id = $shop -> shop_id;
            }

            $count++;
        }
        echo '</tbody>';
        echo '</table>';