如何交换阵列中的两个值与索引? [英] How to swap two values in array with indexes?
本文介绍了如何交换阵列中的两个值与索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有一个这样的数组 $阵列=('A'=> 2,'B'=大于1,'C'=> 4);
,我需要换 A
与 C
来得到这个 $阵列=( 'C'=→4,'b'=> 1,'A'=> 2);
。 WHT是这样做的,而无需创建新的数组的最佳方式?我知道这是可能的XOR,但我也需要保存索引。
For example i have an array like this $array = ('a' => 2, 'b' => 1, 'c' => 4);
and i need to swap a
with c
to get this $array = ('c' => 4, 'b' => 1, 'a' => 2);
. Wht is the best way for doing this without creating new array? I know that it is possible with XOR, but i also need to save indexes.
推荐答案
array_splice
将是完美的,但不幸的是它在插入不preserve键阵列。所以你不得不求助于多一点手工切片和切块:
array_splice
would be perfect, but unfortunately it doesn't preserve the keys in the inserted arrays. So you'll have to resort to a little more manual slicing and dicing:
function swapOffsets(array $array, $offset1, $offset2) {
list($offset1, $offset2) = array(min($offset1, $offset2), max($offset1, $offset2));
return array_merge(
array_slice($array, 0, $offset1, true),
array_slice($array, $offset2, 1, true),
array_slice($array, $offset1 + 1, $offset2 - $offset1 - 1, true),
array_slice($array, $offset1, 1, true),
array_slice($array, $offset2 + 1, null, true)
);
}
这篇关于如何交换阵列中的两个值与索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文