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)?
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"}
You can use array_flip() for this.
$array = array(1 => 'one', 2 => 'two');
$arrayFlipped = array_flip($array);
/*
$arrayFlipped:
Array
(
[one] => 1
[two] => 2
)
*/
$reverse = array_reverse($array, true);
$json = json_encode ($reverse);
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 );
?>
$arr = array(
1 => "something",
2 => "somethingelse",
4 => "this"
);
$arr = array_reverse($arr,true); // true!
echo json_encode($arr);
Example:
$arr = array("apple","banana","orange");
$reversed = array_reverse($arr,true);
echo json_encode($reversed);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.