foreach( $items as $item) {
$taskid = (int) $goal['goal_id'];
$items[$i]['tasks'] = array();
$items[$i]['tasks'] = array_filter($tasks, function($task, $taskid){
return $task['task_id'] == $taskid;
});
Why is $taskid not being passed to the array_filter function, it returns null if echoed from within but if echoed just after it is set it gives the correct value e.g.
foreach( $items as $item) {
$taskid = (int) $goal['goal_id'];
echo $taskid;
Will return whatever the integer is
The return part of the function also works if I manually set a value i.e
return $task['task_id'] == 2;
Guidance appreciated
The issue is variable scope and function arguments.
First, array_filter expects a function with a single argument, that argument is the value in the position in the array. It doesn't handle keys.
You set $taskid = (int) $goal['goal_id'];
outside of the anonymous function, and you have a local variable of the same name, which is null because array_filter only passes one argument.
foreach( $items as $item) {
$taskid = (int) $goal['goal_id'];
$items[$i]['tasks'] = array();
# Per the OP, you can pass the necessary variable in via 'use'
$items[$i]['tasks'] = array_filter($tasks, function($task) use($taskid){
return $task['task_id'] == $taskid;
});
}
The array_filter
function passes in an arrays values into a callback function one-by-one. You cannot pass other parameters in with the anonymous callback function like you are attempting to do.
A valid example would be:
$array = ["Bob","Sam","Jack"];
print_r(
array_filter(
$array,
function($value) {
return ($value !== 'Jack');
}
)
);
Returns
Array ( [0] => Bob [1] => Sam )
Thanks guy once you pointed out it was vairiable scope and anonymous functions it was easy enough to fix by referencing in function closure.
$items[$i]['tasks'] = array_filter($tasks, function($task) use(&taskid){
return $task['task_id'] == $taskid;
});