如何对json字符串进行排序? [英] how to sort json string?

查看:1566
本文介绍了如何对json字符串进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to parse the JSON string below into an associative array, sort it by the 'age' field and output the sorted array as an HTML table:

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

?>

我应该使用某种json_decode来打印各个值并在php中使用现有的排序功能吗?

Should I use some sort of json_decode to print the individual values and use an existing sorting function in php?

推荐答案

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

Yes, the only way (I know of) is to use:

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

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

// And sort
sort( $array);

Php提供了许多数组排序功能,只需浏览手册即可.我还从

Php offers many array sorting functions, just browse manual. I also borrowed objectToArray from this page.

我想您可能要按年龄(或姓名)进行排序,您应该使用

I guess you will want to sort by age (or name), you should probably use usort:

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');

这篇关于如何对json字符串进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆