So i have this function that works great at adding up the sum of all values of a specific field in an array, in this case num_sold
So the array is something like this
array(4) {
[0]=>
array(2) {
["num_sold"]=>
string(1) "6"
["id_product"]=>
string(1) "2"
}
[1]=>
array(2) {
["num_sold"]=>
string(1) "6"
["id_product"]=>
string(1) "3"
}
[2]=>
array(2) {
["num_sold"]=>
string(1) "4"
["id_product"]=>
string(1) "4"
}
[3]=>
array(2) {
["num_sold"]=>
string(1) "5"
["id_product"]=>
string(1) "7"
}
}
// this correctly returns 21
$total = array_sum(array_map(
function($element){
return $element['num_sold'];
},
$array));
Now i want to be able to reuse this function on other field names so i wanted to create a function however the $field value isn't getting through. In php storm it says the $field value in sumFieldArray($field,$array) is not used anywhere but its clearly in the function.
I'm guessing it might be a scope issue so i tried doing global $field on the first line but that made no difference and instead it now says the global $field is not used anywhere. What am i doing wrong.
public static function sumFieldArray($field,$array)
{
$field_sum = array_sum(array_map(
function($element, $field){
return $element[$field];
},
$array));
return $field_sum;
}
parent $varorgrandparent $varscoping ability.use()option in function expressions.