Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何对json字符串排序?_Php_Json - Fatal编程技术网

Php 如何对json字符串排序?

Php 如何对json字符串排序?,php,json,Php,Json,我想将下面的JSON字符串解析为一个关联数组,按“age”字段对其排序,并将排序后的数组作为HTML表输出: <? $json='[{"name": "jesse","age": 25},{"name": "jason","age": 29},{"name": "johnson","age": 24}]'; ?> 我是否应该使用某种json_解码来打印单个值,并使用php中现有的排序函数?您可以json_解码字符串,该字符串将为您提供一个关联数组的php数组。从那里,您可以使

我想将下面的JSON字符串解析为一个关联数组,按“age”字段对其排序,并将排序后的数组作为HTML表输出:

<?
$json='[{"name": "jesse","age": 25},{"name": "jason","age": 29},{"name": "johnson","age": 24}]';

?>


我是否应该使用某种json_解码来打印单个值,并使用php中现有的排序函数?

您可以
json_解码
字符串,该字符串将为您提供一个关联数组的php数组。从那里,您可以使用php内置的排序功能对所需的键进行排序。

是的,唯一的方法(我知道)是使用:

$array = json_decode( $json);
$array = array_map( $array, 'objectToArray');

// Or rather:
$array = json_decode( $json, true);

// And sort
sort( $array);
Php提供函数,只需浏览手册即可。我还从中借用了
objectToArray

我想您可能希望按年龄(或姓名)排序,您可能应该使用:

function cmp( $a, $b){
  if( !isset( $a['age']) && !isset( $b['age'])){
    return 0;
  }

  if( !isset( $a['age'])){
    return -1;
  }

  if( !isset( $b['age'])){
    return 1;
  }

  if( $a['age'] == $b['age']){
    return 0;
  }

  return (($a['age'] > $b['age']) ? 1 : -1);
}

usort( $array, 'cmp');