Reverse an associative array with preserving keys in PHP

与世无争的帅哥 提交于 2019-12-05 21:41:51

问题


I spent half an hour but I haven't found a solution.

Following example of an array:

array(14) {
  ["label_text"]=> string(10) "Label text"
  ["e-mail"]=> string(6) "E-Mail"
  ["company"]=> string(7) "Company"
  ["last_name"]=> string(9) "Last name"
  ["first_name"]=> string(10) "First name"
}

What I want to do is just reverse the elements, so that the result is this:

array(14) {
  ["first_name"]=> string(10) "First name"
  ["last_name"]=> string(9) "Last name"
  ["company"]=> string(7) "Company"
  ["e-mail"]=> string(6) "E-Mail"
  ["label_text"]=> string(10) "Label text"
}

There must be a native php for this, but I think I'm blind. I just don't know which function to use.

Any help appreciated!


回答1:


use array_reverse().

array array_reverse ( array $array [, bool $preserve_keys = false ] )

Takes an input array and returns a new array with the order of the elements reversed.

Note: make sure you read the documentation about the 2nd argument of said function.




回答2:


What about the reverse function array_reverse ?

$reversed = array_reverse($array, true);

Doc: http://php.net/manual/en/function.array-reverse.php




回答3:


You're looking for the array_reverse() function:

$new_array = array_reverse($old_array);



回答4:


Just do it like this:

$reversed = array_combine(
   array_reverse(array_keys($arr)),
   array_reverse(array_values($arr))
);


来源:https://stackoverflow.com/questions/15642376/reverse-an-associative-array-with-preserving-keys-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!