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

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

输出:

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

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

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

输出:

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
)

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

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

输出:

Array
(
  [0] => 1760
  [1] => 1199
  [2] => 4188
  [3] => 1552
  [4] => 6388
)
Array
(
  [0] => 1760
  [1] => 9999
  [2] => 8999
  [3] => 1552
  [4] => 6388
)
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.