Kelvin Kelvin - 4 months ago 7
PHP Question

how to calculate data in multidimensional array php

guys is that possible to calculate between

(+,-,*,/)
in multidimensional array?

example i have a multidimensional array in
$menu_info
with this following code :

array(3) {
[0]=>
array(5) {
["menu_order_id"]=>
string(3) "190"
["menu_name"]=>
string(13) "Golden Salmon"
["menu_variant"]=>
string(0) ""
["qty"]=>
string(1) "1"
["price"]=>
string(4) "15.4"
}
[1]=>
array(5) {
["menu_order_id"]=>
string(3) "191"
["menu_name"]=>
string(13) "Golden Salmon"
["menu_variant"]=>
string(0) ""
["qty"]=>
string(1) "1"
["price"]=>
string(4) "15.4"
}
[2]=>
array(5) {
["menu_order_id"]=>
string(3) "192"
["menu_name"]=>
string(13) "Golden Salmon"
["menu_variant"]=>
string(0) ""
["qty"]=>
string(1) "1"
["price"]=>
string(4) "15.4"
}
}


i want trying to calculate all of the
price*qty
like
(15*1)+(15*1)+(15*1)

guys how to count the multidimensional array using math operator ?

thank you very much (:

p.s the length of array can be change.

Answer

You can try this:

$sum = array_sum(array_map(function($item) {
    return $item['price']*$item['qty'];
}, $menu_info));

With some more explanation on your specific issue, I may be able to assist you in better alternatives.

Comments