我有下一个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);我得到的东西是:
Name1Name1Name1Name2Name2
我希望显示如下内容:
3 x Name1 2 x Name2
OR
3 x Name1,2 x Name2
可以做到这一点吗?
答案 0 :(得分:5)
SQL查询将是这样的:
select name,count(name) from table group by name ;
希望这会对你有所帮助。
答案 1 :(得分:1)
您可能希望按标题分组并计算每个分组的出现次数。
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
答案 2 :(得分:1)
您可以像这样使用count(*)组功能关闭组
$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"];
}
这应该有用......
答案 3 :(得分:1)
如果您想使用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}, ";
}
答案 4 :(得分:1)
好的,我终于能够做出我想要的东西了,所以我想在这里分享以备将来使用。
这就是我所做的:
$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;
}
}
感谢大家的帮助。我向每个人添加了分数!