duanjia7607 2017-03-07 10:49
浏览 111
已采纳

php array_filter过滤太多了

Here is the code :

<?php 
$a_campagnes = $this->campagne->get_campagnes_client();
foreach($a_campagnes as $o_camp){
    if($o_camp->groupes){
        foreach($o_camp->groupes as $o_groupe){
            if($o_groupe->IDGroupe == $this->session->o_user->IDGroupe){ echo 'ok';}
        }
    }
}
$a_campagnes = array_filter($a_campagnes, function($o_camp){
    if($o_camp->groupes){
        foreach($o_camp->groupes as $o_groupe){
            if($o_groupe->IDGroupe == $this->session->o_user->IDGroupe) return true;
        }
    }
    return false;
});

$a_campagnes contains at first 10 objects

The result of the first foreach is okokokok

The result of $a_campagnes after the array_filter (which is the same code as the first foreach) is null

Where are the four objects matching my first foreach?

EDIT

Just tried that piece of code:

$i_id_groupe_user = $this->session->o_user->IDGroupe;
        foreach($a_campagnes as $o_camp){
            if($o_camp->groupes){
                foreach($o_camp->groupes as $o_groupe){
                    if($o_groupe->IDGroupe == $i_id_groupe_user){ echo 'ok';}
                }
            }
        }
        $a_campagnes = array_filter($a_campagnes, function($o_camp) use ($i_id_groupe_user){
            if($o_camp->groupes){
                foreach($o_camp->groupes as $o_groupe){
                    if($o_groupe->IDGroupe == $i_id_groupe_user) return true;
                }
            }
            return false;
        });

It gives the same result as before

  • 写回答

1条回答 默认 最新

  • douwen9540 2017-03-07 11:07
    关注

    $this doesn't exist inside anonymous functions, and you're trying to use it as if it was inside your class scope, which would be even less logical.

    If you want to use whatever $this->session is inside your array_filter() callback, you'll have to either declare a class method specifically for that, or tell the anonymous function that it can use it, like this:

    $session = $this->session;
    $a_campagnes = array_filter($a_campagnes, function($o_camp) use ($session) {
        if ($o_camp->groupes) {
            foreach($o_camp->groupes as $o_groupe) {
                if ($o_groupe->IDGroupe == $session->o_user->IDGroupe) return true;
            }
        }
    
        return false;
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多