本文介绍了反向数组值,同时保持键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是一个数组我有:
$a = array('a' => 'a1', 'b' => 'a2', 'c' => 'a3', 'd' => 'a4', 'e' => 'a5');
我想这样做的是扭转数组的值,同时保持完好钥匙,换句话说,它应该是这样的:
What I would like to do is reverse the values of the array while keeping the keys intact, in other words it should look like this:
$a = array('a' => 'a5', 'b' => 'a4', 'c' => 'a3', 'd' => 'a2', 'e' => 'a1');
我应该如何去做?
How should I go about it?
P.S。我试着用 array_reverse()
,但它似乎没有工作。
P.S. I tried using array_reverse()
but it didn't seem to work
推荐答案
一些一步一步的使用PHP函数处理(这可能是COM pressed用更少的变量):
Some step-by-step processing using native PHP functions (this can be compressed with less variables):
$a = array('a' => 'a1', 'b' => 'a2', 'c' => 'a3', 'd' => 'a4', 'e' => 'a5');
$k = array_keys($a);
$v = array_values($a);
$rv = array_reverse($v);
$b = array_combine($k, $rv);
var_dump($b);
结果:
array(5) {
'a' =>
string(2) "a5"
'b' =>
string(2) "a4"
'c' =>
string(2) "a3"
'd' =>
string(2) "a2"
'e' =>
string(2) "a1"
}
这篇关于反向数组值,同时保持键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!