我有一个PHP数组,分配给$terms
,来自Wordpress,在打印时看起来像这样:
Array ( [0] => WP_Term Object (
[term_id] => 19
[name] => Tshirts
[slug] => tshirts
[term_group] => 0
[term_taxonomy_id] => 19
[taxonomy] => clothes
[description] =>
[parent] => 0
[count] => 6
[filter] => raw
)
[1] => WP_Term Object (
[term_id] => 30
[name] => Pants
[slug] => pants
[term_group] => 0
[term_taxonomy_id] => 30
[taxonomy] => clothes
[description] =>
[parent] => 0
[count] => 12
[filter] => raw
)
)
我正在尝试使用in_array()
来检查数组中是否存在值,但是我遇到了麻烦,因为数组包含的参数多于类别。假设我想看看这个阵列中是否存在裤子,这是我尝试过的:
if (in_array('pants', $terms)) {
echo "Pants in array";
}
如何修改此if语句,以便检查pants
在此数组中是否存在slug
?
答案 0 :(得分:3)
您可以组合使用array_search
和array_column
。您也希望将WP_Term
对象转换为数组。幸运的是,它有一个to_array()
方法,因此我们可以在搜索项目之前使用array_map
在我们的函数中进行转换:
var_dump(termsContainsSlug('pants', $terms)); // bool(true)
function termsContainsSlug($slug, $terms) {
$terms = array_map(function($term) { return $term->to_array(); }, $terms);
return array_search($slug, array_column($terms, 'slug')) > 0;
}
答案 1 :(得分:2)
首先,你应该将每个对象转换为一个数组,然后测试是否有任何'裤子'价值观。
foreach($terms as $term) {
if (in_array('pants', (array)$term)) {
echo "Pants in array";
}
}
这应该转换WP_Term对象 - >阵列
(array)$term