首页 > 解决方案 > 如何根据php中的字段过滤数组?

问题描述

我有一个如下所示的 php 代码:

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

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

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()方法,但我不确定如何使用它。

标签: phparrayswordpress

解决方案


使用array_filter()and use,您将在按值过滤多维数组时获得更大的灵活性

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

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

print_r($expected);

推荐阅读