反转数组并保留重复键

时间:2015-06-25 14:12:59

标签: php html arrays

我有这个数组:

Array ( [7] => 12 [5] => 11 [4] => 11 [2] => 9 [8] => 7 [1] => 6 [3] => 6 [6] => 5 [23] => 3 [31] => 2 [32] => 0 [30] => 0 [29] => 0 [21] => 0 [24] => 0 [22] => 0 )

我需要翻转数组,然后重置密钥,使其像[0] => 7 [1] => 5 ...

一样启动

所以我这样做了:

//Flips the array
$arrayEquipas = array_flip($arrayOrdem);
//Resets the keys
$arrayEquipas = array_values($arrayEquipas);

问题是,当我翻转数组时,它会合并重复的键(以前是值),我不希望这种情况发生。关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:4)

将执行您array_keys的功能。
它将提取所有键,并将它们映射到新的数字数组。

开始:

Array ( [7] => 12 [5] => 11 [4] => 11 [2] => 9 [8] => 7 [1] => 6 [3] => 6 [6] => 5 [23] => 3 [31] => 2 [32] => 0 [30] => 0 [29] => 0 [21] => 0 [24] => 0 [22] => 0 )

代码:

$arrayEquipas = array_keys($arrayOrdem);

输出:

array (size=16)
  0 => int 7
  1 => int 5
  2 => int 4
  3 => int 2
  4 => int 8
  5 => int 1
  6 => int 3
  7 => int 6
  8 => int 23
  9 => int 31
  10 => int 32
  11 => int 30
  12 => int 29
  13 => int 21
  14 => int 24
  15 => int 22