filter a list by gender

时间:2017-11-10 作者:Deepak Jain

我对WordPress很陌生,我想按性别筛选一个列表。

选择男性选项应过滤列表,以仅显示具有相关信息的男性。

我如何才能做到这一点?

$list = array(
(object) array( \'name\' => \'John\', \'gender\' => \'male\', \'job\' => \'Farmer\' ),
(object) array( \'name\' => \'Paul\', \'gender\' => \'male\', \'job\' => \'Blacksmith\' ),
(object) array( \'name\' => \'Adam\', \'gender\' => \'male\', \'job\' => \'\' ),
(object) array( \'name\' => \'Mike\', \'gender\' => \'male\', \'job\' => \'\' ),
(object) array( \'name\' => \'Jane\', \'gender\' => \'female\', \'job\' => \'Baker\' ),
(object) array( \'name\' => \'Jill\', \'gender\' => \'female\', \'job\' => \'Farmer\' ),
);

2 个回复
最合适的回答,由SO网友:Rarst 整理而成

WP core中有一个方便的助手函数,名为wp_list_filter().

简单如:

$male = wp_list_filter( $list, [ \'gender\' => \'male\' ] );

SO网友:Drupalizeme

这也可以通过“旧”时尚PHP实现(除了WPwp_list_filter):

我倾向于选择这种解决方案,因为你可以有更多的选择。

 $only_males = array_filter(
        $list,
        function ($e) {
            return $e->gender == \'male\';
        }
    );
将返回:

Array
(
    [0] => stdClass Object
        (
            [name] => John
            [gender] => male
            [job] => Farmer
        )

    [1] => stdClass Object
        (
            [name] => Paul
            [gender] => male
            [job] => Blacksmith
        )

    [2] => stdClass Object
        (
            [name] => Adam
            [gender] => male
            [job] => 
        )

    [3] => stdClass Object
        (
            [name] => Mike
            [gender] => male
            [job] => 
        )

)

结束

相关推荐

当返回值为空时,Apply_Filters为什么要返回非空字符串?

因为这个把我的键盘弄坏了。进行了正确的安装,将数据库上载到新的MySQL,并一直在正确使用子主题。但有件事困扰着我,我想不出来。在我的新安装上(ver2.whowhatwhy.com) 我故意将一些小部件留空。我想,当阅读default-widgets.php wp中的文件包括在该小部件上不会显示标题元素。相反,显示标题小部件是因为,出于某种原因,传递的值apply_filters 是一个空格,而不是空白值$instance[\'title\'] 为空。$title = apply_filters( \'