PHP array_sum 输出单个数字而不是整体

标签 php html mysql pdo

我有这个“优惠券”列表,每个优惠券都有一个唯一的“productid”

coupons

现在我尝试使用以下方法将列表转换为数组:

$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/

相关文章:

php - 列出某个位置特定半径内的点?

php - Symfony2 - 如何设置自定义 CORS header ?

html - CSS 位置问题

mySQL 查询返回 3 列,我想从连接成逗号分隔字符串的一列中获取值

php - 通过 php 调用网络服务 -> 错误 : no transport found or selected transport is not yet supported

php - 我们可以在 <noscript> 标签中使用 php 吗?代码会验证吗?

javascript - 使文本自动更改和随机化

html - 最大宽度为 100% 的 CSS 网格 minmax()

php - 设置默认 View 值标志时 Magento 的行为很奇怪

php - 2 在一个 json 对象上的不同数组中选择查询