本文介绍了保留键的同时反转数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我拥有的一个数组:
Here is an array I have:
$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');
我应该怎么做?
附言我尝试使用 array_reverse()
但它似乎不起作用
P.S. I tried using array_reverse()
but it didn't seem to work
推荐答案
一些使用原生 PHP 函数的逐步处理(这可以用较少的变量进行压缩):
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"
}
这篇关于保留键的同时反转数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!