php array_filter在对象数组上返回空数组

时间:2015-10-29 23:47:57

标签: php arrays array-filter

我想过滤小回调的对象列表,在这一小段代码上得到了这种奇怪的行为:

var_dump($product_categories[90]->slug);
var_dump($last_part);
var_dump($last_part==$product_categories[90]->slug);
$req_obj = array_filter($product_categories, 
                        function($a)
                            {
                                if ((string)$a->slug == $last_part) return true;
                            });
var_dump($req_obj);

它给出这样的输出,无法弄清楚为什么最终数组$ req_obj是空的? :/

string 'bobby' (length=5)
string 'bobby' (length=5)
boolean true
array (size=0)
  empty

$ product_categories的var_dump:

array (size=177)
  0 => 
    object(stdClass)[5988]
      public 'term_id' => string '38' (length=2)
      public 'name' => string 'bobby' (length=22)
      public 'slug' => string 'bobby' (length=12)
      public 'term_group' => string '0' (length=1)
      public 'term_taxonomy_id' => string '1369' (length=4)
      public 'taxonomy' => string 'product_cat' (length=11)
      public 'description' => string '...'
      public 'parent' => string '0' (length=1)
      public 'count' => int 591
      public 'meta_id' => string '1519' (length=4)
      public 'woocommerce_term_id' => string '38' (length=2)
      public 'meta_key' => string 'order' (length=5)
      public 'meta_value' => string '1' (length=1)
  1 => 
    object(stdClass)[5983]
    ...

2 个答案:

答案 0 :(得分:2)

$last_part超出范围:

function($v) use($last_part){
    return $v->slug == $last_part;
}

答案 1 :(得分:1)

试试这个:

 var_dump($product_categories[90]->slug);
 var_dump($last_part);
 var_dump($last_part==$product_categories[90]->slug);
 $req_obj = array_filter($product_categories[90] 
                    function($a) use ($last_part)
                        {
                            if ((string)$a->slug == $last_part) return true;
                        });
 var_dump($req_obj);