我有这个“优惠券”列表,每个优惠券都有一个唯一的“productid”
现在我尝试使用以下方法将列表转换为数组:
$claimed = array($rowOrder['productid']);
我的问题是,当我尝试使用“count”和“array_sum”时,它会输出单独的数字:
$count_claimed = array(count($claimed));
echo array_sum($count_claimed);
使用我得到的 echo 和输出:“1111111” 我应该更改什么以获得 7 的总数? (以“优惠券”数量显示)
附加信息:
SELECT
语句正在输出“优惠券”,$rowOrder
正在调用它。
public function SelectLst_ByUsrCustomerIDInfo($db, $usrcustomerid) {
$stmt = $db->prepare(
" SELECT o.orderid, o.productid, o.usrcustomerid, o.amount, o.amountrefunded, o.createddate, o.scheduleddate, o.useddate, o.expirationdate, p.photosrc
FROM `order` o LEFT JOIN `product` p ON o.productid = p.productid
WHERE usrcustomerid = :usrcustomerid"
);
$stmt->bindValue(':usrcustomerid', $usrcustomerid, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
这样调用
$lstInfo = $mcOrder->SelectLst_ByUsrCustomerIDInfo($db, $usrcustomerid);
foreach($lstInfo as $rowOrder) {
if (isset($rowOrder['productid']) && ($rowOrder['expirationdate'] > date("Y-m-d H:i:s"))) {
$claimed = array($rowOrder['productid']);
$count_claimed = array(count($claimed));
echo array_sum($count_claimed);
}
}
最佳答案
执行 count($lstInfo)
您将获得获取行的总数(PDOStatement::fetchAll()
返回一个数组,您只需计算其中的元素)。然后,您可以循环结果并在条件为真时递增名为 $claimed
的变量。
$lstInfo = $mcOrder->SelectLst_ByUsrCustomerIDInfo($db, $usrcustomerid);
$total = count($lstInfo);
$claimed = 0;
foreach($lstInfo as $rowOrder) {
if (isset($rowOrder['productid']) && ($rowOrder['expirationdate'] > date("Y-m-d H:i:s"))) {
$claimed += 1;
}
}
echo "Claimed $claimed of $total.";
更好的是,您可以使用 COUNT()
和添加的 WHERE
条件在一个查询中执行此操作。这意味着你不会得到总数,但这似乎也不是开始的问题。
$stmt = $db->prepare("SELECT COUNT(productid) as cnt
FROM `order` o
LEFT JOIN `product` p
ON o.productid = p.productid
WHERE usrcustomerid = :usrcustomerid
AND expirationdate > NOW()
GROUP BY usrcustomerid");
$stmt->execute([":usrcustomerid" => $usrcustomerid]);
$result = $stmt->fetch();
echo "Claimed ".$result['cnt'];
关于PHP array_sum 输出单个数字而不是整体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55234548/