[英]Reverse key value array in JSON (PHP)
I have a key value array in php like this 我在php中有这样的键值数组
[1]=>"something"
[2]=>"somethingelse"
[4]=>"this"
Now i would like to export this as json, reverse the array, but keep the indexes. 现在我想将其导出为json,反转数组,但保留索引。 So the json format would look something like
所以json格式看起来像
{
"4":"this",
"2":"somethingelse"
"1":"something"
}
Is there an easy way to accomplish this (without parsing the json manually)? 有没有简单的方法来完成此操作(无需手动解析json)?
array_reverse
to get this working. array_reverse
中才能正常工作。 <?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_flip() 。
$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. 如果要反转数组的顺序,最好先将其转换为JSON。 You can do this using the
array_reverse()
function, you will need to set the second parameter to TRUE
to preserve the indexes. 您可以使用
array_reverse()
函数执行此操作,您需要将第二个参数设置为TRUE
才能保留索引。
<?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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.