我有一个数组:
$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)
谢谢 :).
我想现在会有一个非常简单的答案,所以我将我的答案扔进一堆:
// 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
| 归档时间: |
|
| 查看次数: |
7448 次 |
| 最近记录: |