[英]PHP array_filter with get_class filter
I have an array of objects, and I want to check if a certain classname is in it. 我有一个对象数组,我想检查其中是否有某个类名。 So I tried:
所以我尝试了:
$all_classnames = array_filter($obj_array, 'get_class');
$found = in_array("classname_to_test", $all_classnames);
Only, $all_classnames still holds the original object array instead of an array of classnames (through get_class). 只有$ all_classnames仍然保留原始对象数组,而不是类名数组(通过get_class)。 Am I missing something here?
我在这里想念什么吗?
You want to use array_map
(which transforms the input array based on the callback function) instead of array_filter
: 您要使用
array_map
(根据回调函数转换输入数组)而不是array_filter
:
$all_classnames = array_map('get_class', $obj_array);
Note that array_map
takes its arguments in the reverse order than the other array functions that use a callback because PHP. 请注意,与使用PHP的其他使用回调的数组函数相比,
array_map
的参数采用相反的顺序。
This is not how the array_filter function works. 这不是array_filter函数的工作方式。 It just filters your array if the callback returns
false
it will remove the element from the array. 它仅过滤数组,如果回调返回
false
,它将从数组中删除该元素。
What you need is array_map 您需要的是array_map
$all_classnames = array_map('get_class', $obj_array);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.