【问题标题】:how to search an array in php?如何在php中搜索数组?
【发布时间】:2011-05-30 15:35:18
【问题描述】:

假设我有一个名称数组,我想要的是我想根据字符串或正则表达式搜索这个特定的数组,然后将找到的匹配项存储在另一个数组中。这可能吗 ?如果是,那么请你给我提示吗?我是编程新手。

【问题讨论】:

  • 你想存储匹配对应的数组的键吗?

标签: php arrays search


【解决方案1】:

在这种情况下,您可能会按照foreach 循环的方式执行一些操作来遍历数组以找到您要查找的内容。

foreach ($array as $value) {
  if ($searching_for === $value) {/* You've found what you were looking for, good job! */}
}

如果你想使用 PHP 内置方法,你可以使用in_array

$array = array("1", "2", "3");
if (in_array("2", $array)) echo 'Found ya!';

【讨论】:

  • 假设数组中有一个名为“google”的元素,即使有人搜索“go”或“l”或“le”或“oo”,我也希望它被选中。那我需要什么样的正则表达式?感谢您的回答。
  • @Harbhag 我实际上认为这值得自己提出问题;)
【解决方案2】:

1) 将字符串存储在 array1 中 2)array2对你想要匹配 3) array3 用于存储匹配项

$array1 = array("1","6","3");
$array2 = array("1","2","3","4","5","6","7");
foreach($array1 as $key=>$value){
  if(in_array($value,$array2))
      $array3[] = $value;
}
echo '<pre>';
print_r($array3);
echo '</pre>';

【讨论】:

    【解决方案3】:

    要提供另一种解决方案,我建议使用 PHP 的内部 array_filter 来执行搜索。

    function applyFilter($element){
      // test the element and see if it's a match to
      // what you're looking for
    }
    
    $matches = array_filter($myArray,'applyFilter');
    

    从 PHP 5.3 开始,您可以使用 anonymous function(与上面的代码相同,只是声明不同):

    $matches = array_filter($myArray, function($element) {
      // test the element and see if it's a match to
      // what you're looking for
    });
    

    【讨论】:

      【解决方案4】:

      您需要做的是使用回调映射数组,如下所示:

      array_filter($myarray,"CheckMatches");
      
      function CheckMatches($key,$val)
      {
          if(preg_match("...",$val,$match))
          {
              return $match[2];
          }
      }
      

      这将为数组中的每个元素运行回调!

      更新为array_filter

      【讨论】:

      • 需要注意的是,这个不会只返回匹配项,它会返回对数组执行回调后的所有元素。
      猜你喜欢
      • 2011-10-22
      • 2011-01-15
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 2016-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多