【问题标题】:How to search string for value using array in PHP?如何在 PHP 中使用数组搜索字符串的值?
【发布时间】:2014-04-04 09:45:18
【问题描述】:

嗨! 我想在数组 $row 中搜索具有类似“CMS”的值的字符串,下面的代码正在搜索确切的“CMS”。

if (mysql_num_rows($sql_result)>0)
  { 
    while ($row = mysql_fetch_assoc($sql_result))
        { $counter++; 
           if (in_array("CMS", $row)) 
               { $cms++; }
          }
    }

如果有人能指导我如何在数组 $row 中搜索字符串以查找值 LIKE "CMS",我将不胜感激。

【问题讨论】:

标签: php arrays string


【解决方案1】:

使用strposserialize

if (mysql_num_rows($sql_result)>0)
  { 
    while ($row = mysql_fetch_assoc($sql_result))
        { $counter++; 
           if (strpos(serialize($row),"CMS")!==false)  //<--- Changed this `if` statement, nothing else
               { $cms++; }
          }
    }

您可以serialize 您的数组,然后执行strpos 来检查needle 是否在数组内。这类似于按照您的要求执行LIKE

【讨论】:

    【解决方案2】:

    遍历行中的每一列并使用strpos

    if (mysql_num_rows($sql_result)>0) 
    { 
        while ($row = mysql_fetch_assoc($sql_result))
        { 
            $counter++; 
            foreach($row as $column)
            {
                if (strpos($column, 'CMS'))
                {
                    $cms++;
                }
            }
        }
    }
    

    【讨论】:

      【解决方案3】:
      if (mysql_num_rows($sql_result)>0)
        { 
          while ($row = mysql_fetch_assoc($sql_result))
              { $counter++; 
                 foreach ($row as $column) {
                    if (strpos($column, "CMS") !== false) {
                        $cms++;
                    }
                 } 
      
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2019-10-30
        • 2011-12-12
        • 1970-01-01
        • 2013-03-31
        • 1970-01-01
        • 2021-09-15
        • 2011-07-22
        • 2018-11-28
        相关资源
        最近更新 更多