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;
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?