php in_array()不匹配

时间:2010-03-06 13:48:05

标签: php arrays

第一个数组称为$ related_docs,第二个数组是$ all_docs。我试图将第一个数组中的“1”值与第二个数组中的“1”值匹配。

    Array
(
    [0] => 1
)
Array
(
    [0] => Array
        (
            [id] => 1
            [type_name] => bla1
        )

    [1] => Array
        (
            [id] => 2
            [type_name] => bla2
        )

    [2] => Array
        (
            [id] => 3
            [type_name] => bla3
        )
    )

我正在尝试查看第一个数组中的任何值是否出现在第二个数组中,但是脚本只打印出“no”。这是为什么?我已经尝试将if()语句中的$ all_docs更改为$ a,但这没有任何区别。

foreach($all_docs as $a)
  {
   if( in_array($related_docs, $all_docs) )   
   {
    print "yes";
   }
   else print "no";
  }

我是否需要在第二个数组中递归搜索?

3 个答案:

答案 0 :(得分:2)

您正在尝试进行递归搜索,in_array()无法执行此操作。它只能非常原始地匹配您搜索的数组的第一级。

也许this implementation递归的in_array()可以满足你的需要。

或者,使用以下内容:

function id_exists ($search_array, $id)
 {
   foreach ($search_array as $doc)
    if ($doc["id"] == $id) return true;

   else return false;

 }

foreach($all_docs as $a)
  {
   if(  id_exists($related_docs, $a) )   
   {
    print "yes";
   }
   else print "no";
  }

答案 1 :(得分:2)

function in_array_multiple(array $needles, array $haystacks) {
foreach($haystacks as $haystack) {
    foreach($needles as $needle) {
        if(in_array($needle, $haystack)) {
            return true;
        }
    }
}
return false;
}

(这是一个迭代函数,而不是递归函数。)

答案 2 :(得分:1)

尝试

$a = array(1);
$b = array(
    array('id' => 1, 'type_name' => 'bla1'),
    array('id' => 2, 'type_name' => 'bla2'),
    array('id' => 3, 'type_name' => 'bla3'),
);

检查$ b中的ID是否存在于$ a中,因此它与您描述的相反,但结果并不重要:

foreach($b as $c) {
    echo in_array($c['id'], $a) ? 'yes' : 'no';
}

它不是通用的,但它可以做你想要的。