如何在php中根据字段过滤数组?

时间:2019-03-20 17:49:38

标签: php arrays wordpress

我有如下所示的php代码:

    $category = get_the_category(); //第A行
 echo '<pre>'; print_r($category); echo '</pre>'; //第B行

第二行的代码返回以下数组;

Array
(
    [0] => WP_Term Object
        (
            [term_id] => 13085
            [name] => Cannabis
            [slug] => democracy_project_cannabis
            [term_group] => 0
            [term_taxonomy_id] => 13085
            [taxonomy] => category
            [description] => Hello World 
            [parent] => 13083
            [count] => 8
            [filter] => raw
            [cat_ID] => 13085
            [category_count] => 8
            [category_description] => Good Morning
            [cat_name] => Cannabis
            [category_nicename] => democracy_project_cannabis
            [category_parent] => 13083
        )

    [1] => WP_Term Object
        (
            [term_id] => 13093
            [name] => Today
            [slug] => today
            [term_group] => 0
            [term_taxonomy_id] => 13093
            [taxonomy] => category
            [description] => 
            [parent] => 0
            [count] => 3
            [filter] => raw
            [cat_ID] => 13093
            [category_count] => 3
            [category_description] => 
            [cat_name] => Today
            [category_nicename] => today
            [category_parent] => 0
        )

)

问题陈述:

我想知道我需要编写什么php代码,以便它根据 [name] => Today 过滤数组。它只需要一个字段,即 [name] => Today

我认为我需要使用array_filter()方法,但不确定如何使用它。

2 个答案:

答案 0 :(得分:0)

定义一个匿名函数,如果属性true返回name == 'Today',否则返回false

$result = array_filter($cats, function($v) { return $v->name == 'Today'; });

答案 1 :(得分:0)

借助array_filter()use,您可以在按值过滤多维数组时获得更大的灵活性

$filterBy = 'Today'; // any index value you want

$expected = array_filter($cats, function ($var) use ($filterBy) {
    return ($var->name == $filterBy);
});

print_r($expected);
相关问题