<?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;
输出与每个页面关联的标签列表,因此我很确定问题是我如何检查"视频"是否在标签列表中。
上面的输出以下列表:Breakfast
Brunch
Budget
Meal
Easy
Lunch
Quick Meals
Supper
Vegetarian
Videos
和Not found
,即使视频在列表中。
我还尝试使用in_array来查找这样的"视频":
if (in_array($tagToFind, $selectedTags, true)) { // search the array for $tagToFind - true = strict
echo ' Found';
} else {
echo ' Not found';
}
但是得到相同的结果 - 我是 php 的新手,如果这很容易,我很抱歉。
任何帮助将不胜感激。
干杯
似乎$selectedTags一个字符串的数组,因为你的foreach
只循环一次
你应该尝试做
$selectedTags = explode(" ",$page->getAttribute($tags->getAttributeKeyHandle()));
然后使用in_array
函数
$page->getAttribute($tags->getAttributeKeyHandle())
似乎返回一个字符串。
在这种情况下
$selectedTags = array($page->getAttribute($tags->getAttributeKeyHandle()));
没有意义 - 你得到一个包含一个长字符串的数组。
你想要的是:
$selectedTags = $page->getAttribute($tags->getAttributeKeyHandle(((;
if(stristr($selectedTags, $tagToFind)){
// do something
}
else{
// do something else
}
那么最好使用....
if(strcmp($tag , $tagToFind))
{
echo "Found";
}
else
{
echo "Not found";
}
愿这对你有用