wp_list_filter()
云策文档标注
概述
wp_list_filter() 是一个 WordPress 函数,用于基于键值对参数过滤对象数组。它本质上是一个包装函数,直接调用 wp_filter_object_list() 来实现功能。
关键要点
- 函数作用:从输入的对象数组中筛选出符合指定键值对参数的对象。
- 参数说明:$input_list 为必需的对象数组;$args 为可选的键值对参数数组,默认为空数组;$operator 为可选的逻辑操作符,支持 'AND'、'OR' 和 'NOT',默认为 'AND'。
- 匹配规则:键代表属性名,值代表属性值。对象可以拥有比参数更多的属性,不影响匹配;使用 'AND' 操作符时,缺少任何指定属性会导致对象被排除。
- 相关函数:如需从匹配对象中提取特定字段,应使用 wp_filter_object_list()。
- 版本历史:自 5.9.0 版本起,该函数被转换为 wp_filter_object_list() 的包装器。
代码示例
$animals = [
[ 'name' => 'alligator', 'fly' => false, 'class' => 'reptile' ],
[ 'name' => 'dog', 'fly' => false, 'class' => 'mammal' ],
[ 'name' => 'cat', 'fly' => false, 'class' => 'mammal' ],
[ 'name' => 'falcon', 'fly' => true, 'class' => 'bird' ],
[ 'name' => 'bat', 'fly' => true, 'class' => 'mammal' ],
];
wp_list_filter( $animals, [ 'class' => 'mammal' ] );
// 返回所有哺乳动物对象
wp_list_filter( $animals, [ 'class' => 'mammal', 'fly' => true ] );
// 返回会飞的哺乳动物对象(仅蝙蝠)
wp_list_filter( $animals, [ 'class' => 'mammal', 'fly' => true ], 'OR' );
// 返回哺乳动物或会飞的对象(狗、猫、猎鹰、蝙蝠)
原文内容
Filters a list of objects, based on a set of key => value arguments.
Description
Retrieves the objects from the list that match the given arguments.
Key represents property name, and value represents property value.
If an object has more properties than those specified in arguments, that will not disqualify it. When using the ‘AND’ operator, any missing properties will disqualify it.
If you want to retrieve a particular field from all matching objects, use wp_filter_object_list() instead.
Parameters
$input_listarrayrequired-
An array of objects to filter.
$argsarrayoptional-
An array of key => value arguments to match against each object.
Default:
array() $operatorstringoptional-
The logical operation to perform.
'AND'means all elements from the array must match.'OR'means only one element needs to match.'NOT'means no elements may match. Default'AND'.
Source
function wp_list_filter( $input_list, $args = array(), $operator = 'AND' ) {
return wp_filter_object_list( $input_list, $args, $operator );
}
Skip to note 2 content
Felipe Elia
Example of usage:
$animals = [ [ 'name' => 'alligator', 'fly' => false, 'class' => 'reptile' ], [ 'name' => 'dog', 'fly' => false, 'class' => 'mammal' ], [ 'name' => 'cat', 'fly' => false, 'class' => 'mammal' ], [ 'name' => 'falcon', 'fly' => true, 'class' => 'bird' ], [ 'name' => 'bat', 'fly' => true, 'class' => 'mammal' ], ]; wp_list_filter( $animals, [ 'class' => 'mammal' ] ); // [ // [ 'name' => 'dog', ... ] // [ 'name' => 'cat', ... ] // [ 'name' => 'bat', ... ] // ] wp_list_filter( $animals, [ 'class' => 'mammal', 'fly' => true ] ); // [ // [ 'name' => 'bat', ... ] // ] wp_list_filter( $animals, [ 'class' => 'mammal', 'fly' => true ], 'OR' ); // [ // [ 'name' => 'dog', ... ] // [ 'name' => 'cat', ... ] // [ 'name' => 'falcon', ... ] // [ 'name' => 'bat', ... ] // ]