【问题标题】:is there a native php function to see if one array of values is in another array?是否有本机 php 函数来查看一个值数组是否在另一个数组中?
【发布时间】:2023-03-23 00:57:01
【问题描述】:

有没有比使用 strpos() 循环更好的方法?

我不是在寻找部分匹配,而不是 in_array() 类型的方法。

示例针和干草堆以及期望的回报:

$needles[0] = 'naan bread';
$needles[1] = 'cheesestrings';
$needles[2] = 'risotto';
$needles[3] = 'cake';

$haystack[0] = 'bread';
$haystack[1] = 'wine';
$haystack[2] = 'soup';
$haystack[3] = 'cheese';

//desired output - but what's the best method of getting this array?
$matches[0] = 'bread';
$matches[1] = 'cheese';

即:

magic_function($haystack, %$needles%) !

【问题讨论】:

  • 不,不会将 breadnaan bread 进行比较。 OP 似乎正在寻找通配符匹配功能。
  • 这适用于非精确匹配吗?
  • Dohh - 错过了naan。比他应该用空格分隔符来分解所有元素,但那根本就不是原生函数。

标签: php


【解决方案1】:
foreach($haystack as $pattern) {
    if (preg_grep('/'.$pattern.'/', $needles)) {
        $matches[] = $pattern;
    }
}

【讨论】:

  • function magic_function($haystack, $needles) { // 上面的代码 :) }
  • 返回一个包含四个元素的数组:面包、奶酪、面包、奶酪
【解决方案2】:

我认为您在问题中混淆了$haystack$needle,因为naan bread 不在大海捞针中,cheesestring 也不在其中。您想要的输出表明您正在 cheesestring 中寻找 cheese。为此,以下方法将起作用:

function in_array_multi($haystack, $needles)
{
    $matches = array();
    $haystack = implode('|', $haystack);
    foreach($needles as $needle) {
        if(strpos($haystack, $needle) !== FALSE) {
            $matches[] = $needle;
        }
    }
    return $matches;
}

对于给定的 haystack 和 needles,它的执行速度是正则表达式解决方案的两倍。不过可能会因不同数量的参数而改变。

【讨论】:

    【解决方案3】:

    我认为你必须自己动手。对array_intersect() 的用户贡献的评论提供了许多替代实现(如this one)。您只需要将匹配的 == 替换为 strstr()

    【讨论】:

      【解决方案4】:
      $data[0] = 'naan bread';
      $data[1] = 'cheesestrings';
      $data[2] = 'risotto';
      $data[3] = 'cake';
      
      $search[0] = 'bread';
      $search[1] = 'wine';
      $search[2] = 'soup';
      $search[3] = 'cheese';
      
      preg_match_all(
          '~' . implode('|', $search) . '~',
          implode("\x00", $data),
          $matches
      );
      
      print_r($matches[0]); 
      
      // [0] => bread
      // [1] => cheese
      

      如果你告诉我们更多关于真正的问题,你会得到更好的答案。

      【讨论】:

        猜你喜欢
        • 2012-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-28
        相关资源
        最近更新 更多