php数组数据比较大小,PHP 用回调函数比较数据来计算数组的差集

I think the example given here using classes is convoluting things too much to demonstrate what this function does.

array_udiff() will walk through array_values($a) and array_values($b) and compare each value by using the passed in callback function.

To put it another way, array_udiff() compares $a[0] to $b[0], $b[1], $b[2], and $b[3] using the provided callback function.  If the callback returns zero for any of the comparisons then $a[0] will not be in the returned array from array_udiff().  It then compares $a[1] to $b[0], $b[1], $b[2], and $b[3].  Then, finally, $a[2] to $b[0], $b[1], $b[2], and $b[3].

For example, compare_ids($a[0], $b[0]) === -5 while compare_ids($a[1], $b[1]) === 0.  Therefore, $a[1] is not returned from array_udiff() since it is present in $b.

$a = array(

array(

'id' => 10,

'name' => 'John',

'color' => 'red',

),

array(

'id' => 20,

'name' => 'Elise',

'color' => 'blue',

),

array(

'id' => 30,

'name' => 'Mark',

'color' => 'red',

),

);

$b = array(

array(

'id' => 15,

'name' => 'Nancy',

'color' => 'black',

),

array(

'id' => 20,

'name' => 'Elise',

'color' => 'blue',

),

array(

'id' => 30,

'name' => 'Mark',

'color' => 'red',

),

array(

'id' => 40,

'name' => 'John',

'color' => 'orange',

),

);

function compare_ids($a, $b)

{

return ($a['id'] - $b['id']);

}

function compare_names($a, $b)

{

return strcmp($a['name'], $b['name']);

}

$ret = array_udiff($a, $b, 'compare_ids');

var_dump($ret);

$ret = array_udiff($b, $a, 'compare_ids');

var_dump($ret);

$ret = array_udiff($a, $b, 'compare_names');

var_dump($ret);

?>

Which returns the following.

In the first return we see that $b has no entry in it with an id of 10.

array(1) {

[0]=>

array(3) {

["id"]=>

int(10)

["name"]=>

string(4) "John"

["color"]=>

string(3) "red"

}

}

?>

In the second return we see that $a has no entry in it with an id of 15 or 40.

array(2) {

[0]=>

array(3) {

["id"]=>

int(15)

["name"]=>

string(5) "Nancy"

["color"]=>

string(5) "black"

}

[3]=>

array(3) {

["id"]=>

int(40)

["name"]=>

string(4) "John"

["color"]=>

string(6) "orange"

}

}

?>

In third return we see that all names in $a are in $b (even though the entry in $b whose name is 'John' is different, the anonymous function is only comparing names).

array(0) {

}

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值