标签:php
我有一个数组:
$array = array('a' => 'val1', 'b' => 'val2', 'c' => 'val3', 'd' => 'val4');
如何交换任意两个键,使阵列的顺序不同?例如.生成这个数组:
$array = array('d' => 'val4', 'b' => 'val2', 'c' => 'val3', 'a' => 'val1');
谢谢 :).
解决方法:
我以为现在会有一个非常简单的答案,所以我会把我扔进去:
// 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;
这是交换数组的第一个和最后一个元素,保留键.我原本以为你最初想要array_flip(),所以我希望我能正确理解.
标签:php
来源: https://codeday.me/bug/20190518/1126519.html