在php中查找数组中的匹配条目

时间:2014-04-04 06:53:40

标签: php array-intersect

所以我有两个数组:

1. $users_populated = users_populated: Array
(
    [0] => Array
        (
            [id] => 10000106
            [username] => 
            [name] => 
            [firstname] => 
            [initial] => 
            [surname] => 
        )

    [1] => Array
        (
            [id] => 10000106
            [username] => 
            [name] =>  
            [firstname] => 
            [initial] => 
            [surname] => 
            [email] => 
            [role] => 
            [roleids] => 
            [platform] => 
        )

    [2] => Array
        (
            [id] => 10000065
            [username] => 
            [name] =>  
            [firstname] => 
            [initial] => 
            [surname] => 
            [email] => 
        )

    [3] => Array
        (
            [id] => 296
            [username] =>
            [name] =>
            [firstname] => 
            [initial] => 
            [surname] => 
            [email] => 
                  )

    [4] => Array
        (
            [id] => 297
            [username] =>
            [name] =>
            [firstname] =>
            [initial] => 
            [surname] =>
            [email] => 
           )
        )

2. $user_list: Array
(
    [0] => 10000106
    [1] => 297
)

所以我想要第一个数组中与第二个数组匹配的值 这是条目:

$output = output: Array
(
[0] => Array
        (
            [id] => 10000106
            [username] => 
            [name] => 
            [firstname] => 
            [initial] => 
            [surname] => 
        )
 [1] => Array
        (
            [id] => 297
            [username] =>
            [name] =>
            [firstname] =>
            [initial] => 
            [surname] =>
            [email] => 
           )

)

来自第一个数组的短ID和第二个数组中的值应匹配

我已经尝试过使用数组交叉键,但这并没有解决..

感谢阅读。

3 个答案:

答案 0 :(得分:2)

使用array_uintersect()

$result = array_uintersect($one, $two, function($x, $y)
{
   $x = is_array($x)?$x['id']:$x;
   $y = is_array($y)?$y['id']:$y;
   return $x-$y;
});

- 你的第二个数组是普通的,因此它将直接作用于回调。

答案 1 :(得分:0)

如果要检查两个数组是否包含相同的值, 无论价值观如何?订单,你不能使用" =="或" ==="。 试试这个功能。

<?php
function array_equal($a, $b) {
    return (is_array($a) && is_array($b) && array_diff($a, $b) === array_diff($b, $a));
}
?>

答案 2 :(得分:0)

通过循环$ users_populated和array_seach函数,您可以获得预期的结果。

<?php

$output = array();

// Case 1: This will overlap by using the last appearance of the same ID value if repeated ID appears in $users_populated

foreach($users_populated as $value) {

    if($key = array_search($value['id'], $user_list))

        $output[$key] = $value;

}

// Case 2: This will use the first result found in $users_populated

foreach($users_populated as $value) {

    if(empty($output[$value['id']]) && $key = array_search($value['id'], $user_list))

        $output[$key] = $value;

}

var_dump($output);

希望这就是你想要的。