PHP数组函数array_diff()、array_merge()与数组操作符+

看到此文,是否觉得体内洪荒之力爆发,饥渴难耐想吐槽
本文为转载文章,若有侵权或违规行为,请联系我,会及时处理相关内容。

支付宝微  信

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

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));

输出:

Array
(
    [1] => 1199
    [2] => 4188
    [3] => 1552
    [4] => 6388
)
Array
(
    [1] => 9999
    [2] => 8999
)

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

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));

输出:

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
)

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

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 );

输出:

Array
(
    [0] => 1760
    [1] => 1199
    [2] => 4188
    [3] => 1552
    [4] => 6388
)
Array
(
    [0] => 1760
    [1] => 9999
    [2] => 8999
    [3] => 1552
    [4] => 6388
)

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


分类: PHP, 技术, 编程, 随记 | 标签: , , , | 评论 | Permalink

发表评论

电子邮件地址不会被公开。