为什么将数组键值设置在数组的末尾而不是特定位置?

时间:2018-09-26 21:58:51

标签: php

确切地说,我有:

$foo = [1, 4, 1, 5, 8, 1, 3, 5, 1, 4, 1, 3, 7, 2];
sort($foo);
$bar = array_count_values($foo);

for ($i = 1; $i < count($bar); $i++) {
    if (!isset($bar[$i])) {
        $bar[$i] = 0;
    }
}

实际结果:

array (size=8)
  1 => int 5
  2 => int 1
  3 => int 2
  4 => int 2
  5 => int 2
  7 => int 1
  8 => int 1
  6 => int 0

预期结果:

array (size=8)
  1 => int 5
  2 => int 1
  3 => int 2
  4 => int 2
  5 => int 2
  6 => int 0
  7 => int 1
  8 => int 1

为什么我的键值对6 => 0出现在数组的底部而不是特定位置?

1 个答案:

答案 0 :(得分:2)

这是因为您要向数组添加新值。

要“修复”该问题,请使用template <template <typename...> class C, typename... T> struct wrapper { typedef C<T...> type; }; wrapper<std::vector, int>::type foo; wrapper<std::set , int>::type bar;

@Rob Ruchte在评论中写道,ksort($bar);返回的数组是关联的,这意味着键没有顺序。

http://php.net/manual/en/function.array-count-values.php

  

从数组中返回一个关联的值数组作为键,并将其计数作为值。