在列表中分组 - php

I have mysql result as you can see below. I want to make shop based list, how can I do in 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 PRODUCT PRICE
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

You can use the power of associative nature of PHP arrays: 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) will print:

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"
  }
}

You should also refer to your mysql driver documentation. It is likely that some of its methods will return your data in a similar manner.

try this

$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>
"; 
echo "<p>".$row['PRODUCT']."</p>
"; 
$cat = $row['SHOP P_ID']; 
} 

I have found solution myself, if you have better solution, please share us.

$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>';