找到一个二维数组,以找到多个没有循环的元素之和?

时间:2018-10-31 06:14:12

标签: php arrays

我的数组:

$data = [
0 => [
    "id" => "23",
    "to_user_id" => "6",
    "from_user_id" => "1",
    "month" => "201810",
    "add_time" => "1540795976",
    "f1" => 10,"f2" => 0,"f3" => 0,"f4" => 0, "f5" => 0,"f6" => 55,"f7" => 0,"f8" => 0,"f9" => 77,"f10" => 0,"f11" => 0,"f12" => 99,"f13" => 77,"f14" => 66,"f15" => 55,
    "score" => 0
],
1 => [
    "id" => "24",
    "to_user_id" => "6",
    "from_user_id" => "1",
    "month" => "201810",
    "add_time" => "1540795976",
    "f1" => 10,"f2" => 0,"f3" => 0,"f4" => 0, "f5" => 0,"f6" => 55,"f7" => 0,"f8" => 0,"f9" => 77,"f10" => 0,"f11" => 0,"f12" => 99,"f13" => 77,"f14" => 66,"f15" => 55,
    "score" => 0
]
];

我需要得到f1-f15的总和。这是我的代码:

echo array_sum(array_map(function ($val){
            return $val['f1']+$val['f2']+$val['f3']+$val['f4']+$val['f5']+$val['f6']+$val['f7']+$val['f8']+$val['f9']+$val['f10']+$val['f11']+$val['f12']+$val['f13']+$val['f14']+$val['f15'];
        },$data));

它看起来不太好,是否有更好的实现方法?谢谢!

2 个答案:

答案 0 :(得分:3)

您可以使用带有正则表达式的array_filter仅选择所需的键

$res = [];
foreach($data as $item) {
    $res[] = array_sum(array_filter($item, function ($x) { return preg_match('/^f\d+$/', $x); }, ARRAY_FILTER_USE_KEY ));
}
print_r($res);

demo

答案 1 :(得分:1)

您已经在做的事情略有不同,但是更改了提取项目的方式。这将使用after之后的另一个键数组,然后使用array_intersect_key()过滤掉所有其他值,然后使用array_sum()而不是将每个项目加在一起...

$extract = ["f1" => 0, "f2" => 0, "f3" => 0, "f4" => 0, "f5" => 0,
    "f6" => 0, "f7" => 0, "f8" => 0, "f9" => 0, "f10" => 0, "f11" => 0,
    "f12" => 0, "f13" => 0, "f14" => 0, "f15" => 0 ];

echo array_sum(array_map(function ($val) use ($extract) {
    return array_sum(array_intersect_key($val, $extract));
}, $data));