簡體   English   中英

php-在數組中搜索字符串

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM