3

I have a function below that is called and passed an array. I would also like to pass it a field (or key) name so that it is reusable. When I try to pass $field in the callback as below I get an error that $field is not defined. If I use a literal, it works great.

function array_map_recursive($array,$field) {
        $sum = 0;
        foreach ($array as $key => $value) {
           foreach ($value as $key2 => $value2) {
               $sum += array_sum(array_map(function($item){return $item[$field];},$value[$key2]));
           }
        }
        return $sum;
}

called:

number_format(array_map_recursive($dept_catg_grp_descs,"total_ty_yest_sales"))
user3352316
  • 167
  • 1
  • 1
  • 8

3 Answers3

8
function ($item) use ($field) {return $item[$field];}

This "imports" the $field variable into the function.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

Simple: You need to declare which variables from the outer scope you want to use in your closure, such as:

function array_map_recursive($array,$field) {
    $sum = 0;
    foreach ($array as $key => $value) {
       foreach ($value as $key2 => $value2) {
           $sum += array_sum(array_map(function($item) use($field) {return $item[$field];},$value[$key2]));
       }
    }
    return $sum;
}

Note the use clause.

demonkoryu
  • 1,247
  • 10
  • 27
0

You should pass your parameter with 'use'

fsperrle
  • 1,262
  • 1
  • 14
  • 26