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"))
2

3 Answers 3

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

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

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

Comments

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.

Comments

0

You should pass your parameter with 'use'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.