0

我有 2 个数组,并希望使用 PHP 在其中 1 个数组中找到一个值。

我意识到我必须使用 PHPexplode函数,但恐怕我的技能就到此为止了。

我的函数会比较两个数组的值,如果它$needle在里面找到任何值$haystack,它会在里面返回它们$found。它可能会找到不止一个,所以也许也$found应该是一个数组?

$needle = "Swimming,Landscaping,Gardening,Bricklaying,3D Modelling";
$haystack = "Football,Rugby,Landscaping,3D Modelling";
$found = magicFunction($needle,$haystick); 
// $found['0'] = "Landscaping";
// $found['1'] = "3D Modelling";

这有意义吗?

非常感谢您对此的任何指示。

4

5 回答 5

7

PHP 提供了方便的函数array_intersect来做到这一点。

$needle = "Swimming,Landscaping,Gardening,Bricklaying,3D Modelling";
$haystack = "Football,Rugby,Landscaping,3D Modelling";

$needle = explode(",", $needle);
$haystack = explode(",", $haystack);

$intersection = array_intersect($haystack, $needle);
print_r($intersection);
//Array ( [2] => Landscaping [3] => 3D Modelling )
于 2012-12-19T08:56:09.993 回答
3

你可以这样做:

$found = Array ();
$needle = "Swimming,Landscaping,Gardening,Bricklaying,3D Modelling";
$haystack = "Football,Rugby,Landscaping,3D Modelling";
$search = explode(',',$haystack);
foreach ( explode(',',$needle as $k => $v )
{
  if ( in_array ( $v, $search ) )
    $found[] = $v;
}

或者正如大卫所说,你可以使用array_intersect

$found = array_intersect ( explode( ',', $haystack ), explode( ',', $needle ) );
于 2012-12-19T08:57:11.417 回答
1

您可以从 needle 和 haystack 中生成数组,然后找到两个数组的交集:

<?php

$needle = "Swimming,Landscaping,Gardening,Bricklaying,3D Modelling";
$haystack = "Football,Rugby,Landscaping,3D Modelling";

$needle = explode(',', $needle);
$haystack = explode(',', $haystack);


$found = array_intersect($needle, $haystack);

print_r($found);
?>

http://tr1.php.net/array_intersect

于 2012-12-19T08:58:36.910 回答
1

您正在寻找的功能内置于 PHP:array_intersect中。

$a = explode(',', "Swimming,Landscaping,Gardening,Bricklaying,3D Modelling");
$b = explode(',', "Football,Rugby,Landscaping,3D Modelling");
$found = array_intersect($a, $b); 
print_r($found);

输出: Array ( [1] => Landscaping [4] => 3D Modelling )

于 2012-12-19T09:02:48.410 回答
0

最简单的方法可能是引爆针并使用strpos.

$needles = explode(',', $needle);
foreach ($needles as $n)
{
      if (strpos($n, $haystack)) {  }
}

如果您不需要字符串的位置,Jan Hančič解决方案可能更合适、更快。

于 2012-12-19T08:58:31.933 回答