PHP array_udiff奇怪的行为

时间:2014-09-24 16:32:12

标签: php arrays comparison

我有2个数组,$array0$array1。我们先预先填写它们:

$user01 = array("no" => 1, "name" => "john");
$user02 = array("no" => 2, "name" => "lewis");
$user03 = array("no" => 3, "name" => "dan");

$array0 = array($user01, $user02, $user03, $user04);

$user11 = array("id" => 1, "name" => "john", "attr" => "foo");
$user12 = array("id" => 7, "name" => "mark", "attr" => "bar");

$array1 = array($user11, $user12);

我希望让$array0的所有用户都不在$array1,因此我使用array_udiff

$diff = array_udiff($array0, $array1, function ($userA, $userB) {
  return $userA['no'] == $userB['id'];
});

但是,在匿名比较功能中,如果我执行var_dump $userA$userB,它们似乎都属于$array0,而我的行为是期待$userA属于$array0$userB属于$array1

即,预期的答案是[[2, "lewis"], [3, "dan"]],但我在比较函数的行中得到了“未找到的索引”:“未定义的索引id”。

我错过了array_udiff行为的内容吗?

1 个答案:

答案 0 :(得分:0)

  1. 我很确定PHP希望比较函数的参数可以互换,你需要更改数组索引是常见的,或者在比较函数中实现逻辑来处理这个问题。
  2. 这不是比较函数的工作原理。

      

    如果第一个参数被认为分别小于,等于或大于第二个参数,则比较函数必须返回小于,等于或大于零的整数。

  3. 所以:

    $user01 = array("id" => 1, "name" => "john");  // "no" changed to "id"
    $user02 = array("id" => 2, "name" => "lewis");
    $user03 = array("id" => 3, "name" => "dan");
    
    $array0 = array($user01, $user02, $user03); // non-existant $user04 removed
    
    $user11 = array("id" => 1, "name" => "john", "attr" => "foo");
    $user12 = array("id" => 7, "name" => "mark", "attr" => "bar");
    
    $array1 = array($user11, $user12);
    
    $diff = array_udiff($array0, $array1, function ($userA, $userB) {
        if( $userA['id'] == $userB['id'] ) { return 0; }  // compare function re-jiggered
        else { return $userA['id'] - $userB['id']; }
    });
    
    print_r($diff);
    

    收率:

    Array
    (
        [1] => Array
            (
                [id] => 2
                [name] => lewis
            )
    
        [2] => Array
            (
                [id] => 3
                [name] => dan
            )
    
    )