array_diff()函数是以值为判断依据,比如:

[code lang=”php”]
use Libs\Helper;
include ‘../vendor/autoload.php’;

$a = array (
0 => ‘1760’,
1 => ‘1199’,
2 => ‘4188’,
3 => ‘1552’,
4 => ‘6388’,
);

$b = array(1760, 9999, ‘8999’);

Helper::p(array_diff($a, $b));
Helper::p(array_diff($b, $a));
[/code]

输出:

[code lang=”php”]
Array
(
[1] => 1199
[2] => 4188
[3] => 1552
[4] => 6388
)
Array
(
[1] => 9999
[2] => 8999
)
[/code]

同样,array_merge函数也是以值为判断依据进行合并数组,如下:

[code lang=”php”]
use Libs\Helper;
include ‘../vendor/autoload.php’;

$a = array (
0 => ‘1760’,
1 => ‘1199’,
2 => ‘4188’,
3 => ‘1552’,
4 => ‘6388’,
);

$b = array(1760, 9999, ‘8999’);

Helper::p(array_merge($a, $b));
Helper::p(array_merge($b, $a));

[/code]

输出:

[code lang=”php”]
Array
(
[0] => 1760
[1] => 1199
[2] => 4188
[3] => 1552
[4] => 6388
[5] => 1760
[6] => 9999
[7] => 8999
)
Array
(
[0] => 1760
[1] => 9999
[2] => 8999
[3] => 1760
[4] => 1199
[5] => 4188
[6] => 1552
[7] => 6388
)
[/code]

问题来了,如果利用数组操作符+,进行两个数组的合并,却是以键为判断依据:

[code lang=”php”]
use Libs\Helper;
include ‘../vendor/autoload.php’;

$a = array (
0 => ‘1760’,
1 => ‘1199’,
2 => ‘4188’,
3 => ‘1552’,
4 => ‘6388’,
);

$b = array(1760, 9999, ‘8999’);

Helper::p( $a + $b );
Helper::p( $b + $a );
[/code]

输出:

[code lang=”php”]
Array
(
[0] => 1760
[1] => 1199
[2] => 4188
[3] => 1552
[4] => 6388
)
Array
(
[0] => 1760
[1] => 9999
[2] => 8999
[3] => 1552
[4] => 6388
)
[/code]


文章来源:胡旭个人博客 => 【原】PHP数组函数array_diff()、array_merge()与数组操作符+
转载请注明出处,违者必究!

Share:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.