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

如何在foreach循环中合并SQL结果数组并生成指定结构的新数组?

解决方案

方案一:PHP端转换结果数组

先按员工姓名分组,再将每个员工的两类结果映射为x和y:

// 假设原始查询结果是 $rawResults
$grouped = [];
foreach ($rawResults as $item) {
    $name = $item['employee_first_name'];
    $value = (float)$item['result'];
    if (!isset($grouped[$name])) {
        $grouped[$name] = [];
    }
    // 映射分类到x/y
    if ($item['question_category'] === 'Engagement') {
        $grouped[$name]['x'] = $value;
    } elseif ($item['question_category'] === 'Tenure') {
        $grouped[$name]['y'] = $value;
    }
}
// 提取分组后的数组值,得到目标结构
$results = array_values($grouped);

执行后$results会生成你需要的结构:

array(2) {
  [0]=>
  array(2) {
    ["x"]=>
    float(6.6667)
    ["y"]=>
    float(7.6667)
  }
  [1]=>
  array(2) {
    ["x"]=>
    float(7.6667)
    ["y"]=>
    float(8.3333)
  }
}

方案二:直接通过SQL查询获取目标结构

更高效的方式是在SQL层面直接聚合,避免后续PHP处理:

SELECT
    employee_first_name,
    AVG(CASE WHEN question_category = 'Engagement' THEN result END) AS x,
    AVG(CASE WHEN question_category = 'Tenure' THEN result END) AS y
FROM your_table_name
WHERE question_category IN ('Engagement', 'Tenure')
GROUP BY employee_first_name;

这个查询会直接返回每个员工对应的x(Engagement的平均值)和y(Tenure的平均值),PHP端只需取出结果数组即可,无需额外转换。

注意事项

  • 确保result字段在数据库中是数值类型,若为字符串需先转换(比如CAST(result AS DECIMAL(10,4)))
  • 如需过滤其他分类,调整WHERE条件即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 03:10:35