[英]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;
输出与每个页面关联的标签列表,因此我很确定问题是我如何检查“视频”是否在标签列表中。
上面输出以下列表: 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";
}
可能这对你有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.