dousheng3364 2013-04-25 18:44
浏览 71

传递给array_filter时参数丢失

    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

  • 写回答

3条回答 默认 最新

  • dongzecai0684 2013-04-25 18:55
    关注

    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;
      });
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据