justin
justin

Reputation: 23

Faster way of calulating values in multidimensional array in php?

0 => array(
    'key1' = value
    'key2' = value
    }
1 => array(
    'key1' = value
    'key2' = value
    }

Is there a fast way of getting the sum of id=>key1 and id2=key1 so that I don't have to loop through?

I'd like it to see the array as

array(
    0 = value (key1)
    1 = value (key1)
)

But if it isn't built in somehow, it probably would be another step.

Upvotes: 2

Views: 69

Answers (1)

Mark Baker
Mark Baker

Reputation: 212452

Using PHP 5.5's array_column() function

$result = array_sum(
    array_column(
        $myArray,
        'key1'
    )
);

for PHP < 5.5

$result = array_sum(
    array_map(
        $myArray,
        function ($value) { return $value['key1']; }
    )
);

Upvotes: 1

Related Questions