Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

php - Reverse array values while keeping keys

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');

How should I go about it?

P.S. I tried using array_reverse() but it didn't seem to work

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

Result:

array(5) {
  'a' =>
  string(2) "a5"
  'b' =>
  string(2) "a4"
  'c' =>
  string(2) "a3"
  'd' =>
  string(2) "a2"
  'e' =>
  string(2) "a1"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...