Q: Reverse key value array in JSON (PHP) I have a key value array in php like this
[1]=>"something"
[2]=>"somethingelse"
[4]=>"this"

Now i would like to export this as json, reverse the array, but keep the indexes. So the json format would look something like
{
    "4":"this",
    "2":"somethingelse"
    "1":"something"
}

Is there an easy way to accomplish this (without parsing the json manually)?

A: You need to preserve the keys in the array_reverse to get this working.
<?php
$arr=array(1=>"something",2=>"somethingelse",4=>"this");
echo json_encode(array_reverse($arr,true),true);

OUTPUT :
{"4":"this","2":"somethingelse","1":"something"}


A: You can use array_flip() for this.
$array = array(1 => 'one', 2 => 'two');

$arrayFlipped = array_flip($array);

/*
$arrayFlipped:

Array
(
   [one] => 1
   [two] => 2
)
*/


A: $reverse = array_reverse($array, true);
$json = json_encode ($reverse);


A: If you wish to reverse the order of the array, it's best to do so before conversing it to JSON. You can do this using the array_reverse() function, you will need to set the second parameter to TRUE to preserve the indexes.
<?php
$myArray = Array(
    1 => "something",
    2 => "somethingelse",
    4 => "this"
);

$myJSON = json_encode( array_reverse( $myArray, true ) );

print_r( $myJSON );
?>


A: $arr = array(
    1 => "something",
    2 => "somethingelse",
    4 => "this"
);

$arr = array_reverse($arr,true); // true!

echo json_encode($arr);


A: array_reverse
Example:
$arr = array("apple","banana","orange");
$reversed = array_reverse($arr,true);
echo json_encode($reversed);

