[英]php - search an array for a string
<?php // SEARCH TAGS FOR A SPECIFIC TAG
$tags = CollectionAttributeKey::getByHandle('recipe_tags'); // attribute handle of tags to search
$tagToFind = 'Videos'; // declare the specific tag to find
$selectedTags = array($page->getAttribute($tags->getAttributeKeyHandle())); // get tags associated with each page and put them in an array
foreach ($selectedTags as $tag) { // output tags separately
echo $tag; // ECHO TEST - check that individual tags associated with each page are outputting correctly
if ($tag == $tagToFind) { // if $tag is equal to $tagToFind
echo ' Found';
} else {
echo ' Not found';
}
}
?>
echo $tag;
outputs the list of tags associated with each page so I'm pretty sure the issue is how I'm checking if 'Videos' is in the list of tags. 输出与每个页面关联的标签列表,因此我很确定问题是我如何检查“视频”是否在标签列表中。
The above outputs the following list: Breakfast
Brunch
Budget
Meal
Easy
Lunch
Quick Meals
Supper
Vegetarian
Videos
and Not found
even though Videos is in the list. 上面输出以下列表:
Breakfast
Brunch
Budget
Meal
Easy
Lunch
Quick Meals
Supper
Vegetarian
Videos
和即使在列表中也Not found
视频。
I've also tried using in_array to look for 'Videos' like this: 我也尝试过使用in_array查找“视频”,如下所示:
if (in_array($tagToFind, $selectedTags, true)) { // search the array for $tagToFind - true = strict
echo ' Found';
} else {
echo ' Not found';
}
But get the same result - I'm new to php so sorry if this is easy. 但是得到相同的结果-我是php的新手,如果这很简单,请对不起。
Any help would be much appreciated. 任何帮助将非常感激。
Cheers 干杯
It seems that $selectedTags an array of one string, since your foreach
only loops once 似乎$ selectedTags标记了一个字符串数组,因为您的
foreach
仅循环一次
You should try doing 你应该尝试做
$selectedTags = explode(" ",$page->getAttribute($tags->getAttributeKeyHandle()));
Then use in_array
function 然后使用
in_array
函数
$page->getAttribute($tags->getAttributeKeyHandle())
seems to return a string. 似乎返回一个字符串。
In that case 在这种情况下
$selectedTags = array($page->getAttribute($tags->getAttributeKeyHandle()));
makes no sense - you get an array containing one long string. 没有道理-您得到一个包含一个长字符串的数组。
What you want to to is: 您想要的是:
$selectedTags = $page->getAttribute($tags->getAttributeKeyHandle()); $ selectedTags = $ page-> getAttribute($ tags-> getAttributeKeyHandle());
if(stristr($selectedTags, $tagToFind)){
// do something
}
else{
// do something else
}
Then Better to use.... 然后更好地使用...。
if(strcmp($tag , $tagToFind))
{
echo "Found";
}
else
{
echo "Not found";
}
may this works for you 可能这对你有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.