Reputation: 2654
I am trying to use array map dynamically, the column in the array may change so I don't want to specify it using string but want to use a variable to specify it, it does not work. Tried all the following combinations, it returns null.
$column = 'MANAGER_GROUP';
array_map(function($el){ return $el['"'.$column.'"']; }, $dbData);
array_map(function($el){ return $el["$column"]; }, $dbData);
array_map(function($el){ return $el[$column]; }, $dbData);
//this works though
array_map(function($el){ return $el["MANGER_GROUP"]; }, $dbData);
Upvotes: 3
Views: 613
Reputation: 1903
Anonymous function has it's own scope, it does not have access to parent scope automatically. You have to explicitly specify a variable to be passed to anonymous function context.
$column = 'MANAGER_GROUP';
array_map(function($el) use ($column) {
return $el[$column];
}, $dbData);
Upvotes: 6