如何以数组值为键修改数组?按cutoff分组存储totals值遇阻求助
解决PHP数组按cutoff分组提取totals的问题
正确实现代码
直接遍历原数组完成分组即可,以下是能满足需求的代码:
// 你的原始数组 $originalArray = array( array( "name" => "BIBAR", "cutoff" => 20220725, "totals" => 5614 ), array( "name" => "BIBAR", "cutoff" => 20220810, "totals" => 5614 ), array( "name" => "BIBAR", "cutoff" => 20220825, "totals" => 5614 ), // 增加同cutoff的示例,验证分组效果 array( "name" => "BIBAR", "cutoff" => 20220725, "totals" => 7890 ) ); $result = []; foreach ($originalArray as $item) { // 将cutoff转为字符串键,和你期望的格式一致 $cutoffKey = (string)$item['cutoff']; // 若该键未初始化,先创建空数组 if (!isset($result[$cutoffKey])) { $result[$cutoffKey] = []; } // 将当前项的totals追加到对应分组 $result[$cutoffKey][] = $item['totals']; } print_r($result);
执行后会得到符合预期的结构:
Array ( [20220725] => Array ( [0] => 5614 [1] => 7890 ) [20220810] => Array ( [0] => 5614 ) [20220825] => Array ( [0] => 5614 ) )
原代码的问题分析
你写的代码存在几个关键错误:
- 未定义变量
$cutoffs:循环遍历的$cutoffs没有给出定义,导致循环无法正确执行 array_filter用法错误:这个函数的作用是过滤数组元素,仅保留回调返回值为true的原元素,而非提取totals值。你的回调返回$val['totals']或$val,只会让array_filter判断真假,不会替换元素内容,结果完全不符合预期$ii逻辑混乱:$ii在循环内部每次都重置为0,导致所有数据都被塞进sums[0]下,分组逻辑完全错误
更简洁的写法(用array_reduce)
如果偏好函数式写法,也可以用array_reduce实现:
$result = array_reduce($originalArray, function($carry, $item) { $cutoffKey = (string)$item['cutoff']; $carry[$cutoffKey][] = $item['totals']; return $carry; }, []);
内容的提问来源于stack exchange,提问作者user20476491
相关产品推荐
相关产品推荐

