You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP按产品标题分组多维数组 统计营收并降序排序实现

PHP销售数据分组统计营收实现方案

实现逻辑

核心分3步完成需求:

  • 遍历原始销售交易数组,以product_title为分组键,累加计算每笔交易的营收(quantity * selling_price)得到单产品总营收
  • 使用关联数组降序排序函数,按总营收从高到低排序,保留产品名和营收的键值对应关系
  • 遍历排序后的结果,输出带产品名、总营收两列的表格

完整实现代码

// 原始销售数据(即你从API获取的$sales数组)
$sales = array (
  0 => 
  array (
    'id' => 1,
    'product_title' => 'Product 1',
    'selling_price' => 50.0,
    'quantity' => 1,
  ),
  1 => 
  array (
    'id' => 2,
    'product_title' => 'Product 2',
    'selling_price' => 80.0,
    'quantity' => 2,
  ),
  2 => 
  array (
    'id' => 3,
    'product_title' => 'Product 1',
    'selling_price' => 50.0,
    'quantity' => 8,
  ),
  3 => 
  array (
    'id' => 4,
    'product_title' => 'Product 4',
    'selling_price' => 120.0,
    'quantity' => 3,
  ),
  4 => 
  array (
    'id' => 5,
    'product_title' => 'Product 2',
    'selling_price' => 80.0,
    'quantity' => 3,
  ),
);

$results = array();
// 第一步:分组累加计算总营收
foreach ($sales as $transaction) {
    $productName = $transaction['product_title'];
    // 首次遍历到该产品时初始化营收为0
    if (!isset($results[$productName])) {
        $results[$productName] = 0;
    }
    // 累加当前交易的营收
    $results[$productName] += $transaction['selling_price'] * $transaction['quantity'];
}

// 第二步:按总营收降序排序,保持键值关联
arsort($results);

// 第三步:输出表格
echo "<table border='1' cellpadding='6' cellspacing='0'>";
echo "<tr><th>产品标题</th><th>总营收</th></tr>";
foreach ($results as $productName => $totalRevenue) {
    echo "<tr><td>" . htmlspecialchars($productName) . "</td><td>" . number_format($totalRevenue, 2) . "</td></tr>";
}
echo "</table>";

运行结果说明

针对提供的测试数据,最终排序后的统计结果为:

  • Product 1:总营收450.00
  • Product 2:总营收400.00
  • Product 4:总营收360.00

原代码问题说明

原有代码存在3个核心问题导致无法实现需求:

  • 分组赋值时取$value[0]是错误的,单条交易记录是关联数组,不存在数字键0
  • 没有对同产品的多笔交易做营收累加,同产品的前序记录会被后序记录直接覆盖
  • 缺少排序逻辑,输出时也没有渲染总营收列
  • 补充:实现中增加了htmlspecialchars特殊字符转义和金额格式化处理,避免特殊字符导致的页面异常,也更符合业务展示规范

内容的提问来源于stack exchange,提问作者user9361135

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 09:36:16