Php 在以下情况下如何使用数组搜索
下面是我正在使用的代码,但它不起作用:Php 在以下情况下如何使用数组搜索,php,Php,下面是我正在使用的代码,但它不起作用: $if_existing = "Aishwarya Majmudar"; $key = array_search($if_existing, array_column($all_tags, 'name')); if($key){ echo 'Yes'; } Array ( [0] => WP_Term Object ( [term_id] => 57 [name] =&g
$if_existing = "Aishwarya Majmudar";
$key = array_search($if_existing, array_column($all_tags, 'name'));
if($key){
echo 'Yes';
}
Array
(
[0] => WP_Term Object
(
[term_id] => 57
[name] => Aishwarya Majmudar
[slug] => aishwarya-majmudar
[term_group] => 0
[term_taxonomy_id] => 57
[taxonomy] => post_tag
[description] =>
[parent] => 0
[count] => 2
[filter] => raw
)
[1] => WP_Term Object
(
[term_id] => 60
[name] => Akull
[slug] => akull
[term_group] => 0
[term_taxonomy_id] => 60
[taxonomy] => post_tag
[description] =>
[parent] => 0
[count] => 0
[filter] => raw
)
)
我想看看给定数组中是否存在name值。看起来array_search是我可以使用的最好的函数,但它在我提供的数组中不起作用。如果您使用该类,它会更快、更节省资源。这里有一个简短的例子
class NameFilterIterator extends FilterIterater
{
protected string $name;
public function __construct(Iterator $iterator, string $name)
{
$this->name = $name;
parent::__construct($iterator);
}
public function accept(): bool
{
$term = $this->getInnerIterator()->current();
return $term->name === $this->name;
}
}
这是FilterEditor继承。该类在构造函数中获取name属性,然后在数组中搜索该名称。由于集合是WP_Term对象的数组,因此可以使用对象表示法获取WP_Term
属性。让我们看看如何使用这个
假设您的WP_术语集合存储在$result中
$iterator = new ArrayIterator($result);
$filter = new NameFilterIterator($iterator, 'Aishwarya Majmudar');
foreach ($filter as $term) {
var_dump($term); // returns the term with Aishwarya Majmudar
}
foreach循环现在只返回术语,其name属性为“Aishwarya Majmudar”。ArrayIterator类和FilterIterator类都随PHP提供,并且已经可用。你可以简单地使用它们。它们比阵列函数更快、资源效率更高。只需在主题的functions.php文件中插入
NameFilterIterator
类,您就可以再次使用它了。:“警告:此函数可能返回布尔值FALSE,但也可能返回计算结果为FALSE的非布尔值。有关详细信息,请阅读布尔值部分。使用===运算符测试此函数的返回值。”在数组项中找到要查找的值的键为0
如果(0)
不正确。PHP解析错误:语法错误、意外的“字符串”(T_字符串)、预期函数(T_函数)或常量(T_常量)。当PHP版本<7.4时,会发生此错误。只需在类属性之前省略类型提示,或更新到最新的PHP版本。