交换数组中的两个键/值对

ale*_*ale 5 php

我有一个数组:

$array = array('a' => 'val1', 'b' => 'val2', 'c' => 'val3', 'd' => 'val4');
Run Code Online (Sandbox Code Playgroud)

如何交换任意两个键,使阵列的顺序不同?例如,生成这个数组:

$array = array('d' => 'val4', 'b' => 'val2', 'c' => 'val3', 'a' => 'val1');
Run Code Online (Sandbox Code Playgroud)

谢谢 :).

Wes*_*rch 3

我想现在会有一个非常简单的答案,所以我将我的答案扔进一堆:

// Make sure the array pointer is at the beginning (just in case)
reset($array);

// Move the first element to the end, preserving the key
$array[key($array)] = array_shift($array);

// Go to the end
end($array);

// Go back one and get the key/value
$v = prev($array);
$k = key($array);

// Move the key/value to the first position (overwrites the existing index)
$array = array($k => $v) + $array;
Run Code Online (Sandbox Code Playgroud)

这是交换数组的第一个和最后一个元素,保留键。我以为你array_flip()最初想要的,所以希望我理解正确。

演示: http: //codepad.org/eTok9WA6

  • 我的直觉是,你“真的”不需要这样做,而且你还有另一个问题想要解决,但你选择了这个作为解决方案。也许我错了,但我在这里看到了很多。 (2认同)