1

我有一个像这样的多维数组:

 Array ( 
   [0] => Array ( 
              [id] => 1 
              [name] => privilages1 
              ) 
    [1] => Array ( 
              [id] => 2 
              [name] => privilages2 
              ) 
     [2] => Array ( 
              [id] => 3 
              [name] => privilages3 
                ) 
     [3] => Array ( 
              [id] => 4 
              [name] => privilage4 ) 
     [4] => Array ( 
              [id] => 5 
              [name] => privilages5 ) 
)

我想将它与另一个数组进行比较,如下所示:

Array ( 
     [0] => Array ( 
              [id] => 1 ) 
     [1] => Array ( 
              [id] => 2)
)

如果值id匹配,那么我想要第一个示例中的所有值。

我怎样才能做到这一点?

4

1 回答 1

0

您可以使用array_filter通过提供用户定义的回调函数来过滤所需的数组元素。

这是代码:

$arr = array( array('id' => 1, 'name' => 'foo'),
              array('id' => 2, 'name' => 'bar'),
              array('id' => 3, 'name' => 'baz'),
              array('id' => 4, 'name' => 'wow'));

$ret = array_filter($arr, create_function('$el', 
          'static $search=array(array("id" => 1), array("id" => 2));
           $n=array("id" => $el["id"]);
           return (array_search($n, $search) !== false);'));

print_r($ret);

输出

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => foo
        )

    [1] => Array
        (
            [id] => 2
            [name] => bar
        )

)
于 2012-05-16T14:10:35.517 回答