1

my array:

$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
]
];

I need to get the sum of f1-f15. here is my code:

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));

It doesn't look too good, is there a better way to implement it? thanks!

2 Answers 2

3

You can use array_filter with regex to select only needed keys

$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

Sign up to request clarification or add additional context in comments.

2 Comments

Nice use of array_filter.
Although not entirely sure about the requirement without loop
1

A slight variation on what you are already doing, but changing the way that the items are extracted. This uses another array of the keys your after and then uses array_intersect_key() to filter out all of the other values and then uses array_sum() instead of the adding each item together...

$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));

2 Comments

$extract = array_fill_keys(["f1","f2",..], 0); ?
@splash58, that would also work, more interested in the main processing though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.