我有下一个mysql查询:
$productn = $jdb->query('SELECT t2.title FROM '.DB_PREFIX.'shopping_cart AS t1 LEFT JOIN '.DB_PREFIX.'shop_order_details AS t2 ON t1.shopid WHERE t1.session = "'.smartsql($_SESSION['shopping_cart']).'"');
while ($rowp = $productn->fetch_assoc()) {
// my product title
$productname = $rowp["title"];
}
使用print_r($productname);我得到类似的东西:
名称1名称1名称1名称2名称
2我想显示以下内容:
3 x 名称12 x 名称2
或
3 x 名称1, 2 x 名称2
有可能做到这个吗?
SQL查询将是这样的:
select name,count(name) from table group by name ;
希望这对你有帮助。
如果你想用PHP来做到这一点,请使用:
$total_products = array();
while ($rowp = $productn->fetch_assoc()) {
$productname = $rowp['title'];
if(isset($total_products[$productname])) {
++$total_products[$productname];
}
else
{
$total_products[$productname] = 1;
}
}
UPD 1:以所需格式显示产品:
foreach($total_products as $name => $num) {
echo "{$num} x {$name}, ";
}
你可以像这样使用 count(*) group 函数 group by close
$productn = $jdb->query('SELECT t2.title, count(t2.title) num FROM '.DB_PREFIX.'shopping_cart AS t1 LEFT JOIN '.DB_PREFIX.'shop_order_details AS t2 ON t1.shopid WHERE t1.session = "'.smartsql($_SESSION['shopping_cart']).'" group by t2.title');
while ($rowp = $productn->fetch_assoc()) {
// my product title
$productname = $rowp["title"];
$numberofproducts = $rowp["num"];
}
这应该有效...
好的,我终于能够制作我想要的东西了,所以我想在这里分享它以备将来使用。
这是我所做的:
$productn = $jdb->query('SELECT t2.title, count(t2.title) num FROM '.DB_PREFIX.'shop_order_details AS t2 WHERE t2.orderid ="'.$orderid.'" GROUP BY t2.title');
while($registro=$productn->fetch_array()){
echo $registro['title'].' x '.$registro['num']."<br>";
}
我在类中定义了 fetch_array():
function fetch_assoc() {
if($this->result) {
return mysql_fetch_assoc($this->result);
} else {
return false;
}
}
谢谢大家的帮助。我给大家加了点!
您可能希望按标题分组并计算每个分组的出现次数。
SELECT t2.title, COUNT(t2.title)
FROM shopping_cart AS t1
LEFT JOIN shop_order_details AS t2 ON t1.shopid
WHERE t1.session = <session>
GROUP BY t2.title
查看COUNT(*)
和GROUP BY
函数参考。