Heim >Backend-Entwicklung >PHP-Tutorial >关于array_diff_uassoc的疑问

关于array_diff_uassoc的疑问

WBOY
WBOYOriginal
2016-06-06 20:15:481328Durchsuche

源码:

<code><?php $i = 1;
  function key_compare_func($a, $b)
  {
      global $i;
      var_dump($a);
      var_dump($b);
      echo "=====$i".PHP_EOL;
      if ($a === $b) {
          return 0;
      }
      $i += 1;
      return ($a > $b)? 1:-1;
  }

  $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
  $array2 = array("a" => "green", "yellow", "red");
  $result = array_diff_uassoc($array1, $array2, "key_compare_func");
  print_r($result);</code>

结果:

<code>string(1) "b"
string(1) "a"
=====1
string(1) "b"
string(1) "c"
=====2
int(0)
string(1) "b"
=====3
string(1) "a"
int(0)
=====4
int(0)
string(1) "a"
=====5
int(1)
int(0)
=====6
string(1) "a"
int(0)
=====7
string(1) "a"
string(1) "a"
=====8
int(0)
string(1) "a"
=====8
int(0)
int(0)
=====9
string(1) "b"
string(1) "a"
=====9
string(1) "b"
int(0)
=====10
string(1) "b"
int(1)
=====11
string(1) "c"
string(1) "a"
=====12
string(1) "c"
int(0)
=====13
string(1) "c"
int(1)
=====14
Array
(
    [b] => brown
    [c] => blue
    [0] => red
)
</code>

请问:

<code>对于这个函数,他的比较原理是什么?为什么要进行14次比较?</code>

回复内容:

源码:

<code><?php $i = 1;
  function key_compare_func($a, $b)
  {
      global $i;
      var_dump($a);
      var_dump($b);
      echo "=====$i".PHP_EOL;
      if ($a === $b) {
          return 0;
      }
      $i += 1;
      return ($a > $b)? 1:-1;
  }

  $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
  $array2 = array("a" => "green", "yellow", "red");
  $result = array_diff_uassoc($array1, $array2, "key_compare_func");
  print_r($result);</code>

结果:

<code>string(1) "b"
string(1) "a"
=====1
string(1) "b"
string(1) "c"
=====2
int(0)
string(1) "b"
=====3
string(1) "a"
int(0)
=====4
int(0)
string(1) "a"
=====5
int(1)
int(0)
=====6
string(1) "a"
int(0)
=====7
string(1) "a"
string(1) "a"
=====8
int(0)
string(1) "a"
=====8
int(0)
int(0)
=====9
string(1) "b"
string(1) "a"
=====9
string(1) "b"
int(0)
=====10
string(1) "b"
int(1)
=====11
string(1) "c"
string(1) "a"
=====12
string(1) "c"
int(0)
=====13
string(1) "c"
int(1)
=====14
Array
(
    [b] => brown
    [c] => blue
    [0] => red
)
</code>

请问:

<code>对于这个函数,他的比较原理是什么?为什么要进行14次比较?</code>

查阅了一下源码,在比较之前,PHP还进行了一次排序操作,排序时也会采用这个回调函数,这也就是你会看到结果中会有bc这两个出现在同一个数组中的键进行比较的记录。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn