php - 如何对json字符串进行排序?

标签 php json

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

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

?>

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

最佳答案

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

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

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

// And sort
sort( $array);

Php 优惠 many array sorting功能,只需浏览手册即可。我还从 this page 借用了 objectToArray .

我猜您会想按年龄(或姓名)排序,您可能应该使用 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');

关于php - 如何对json字符串进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9196925/

相关文章:

ios - swift 未转义的控制字符

json - 不带 JSONP 的 getJSON 远程请求 - 服务器

php - 确保多维数组上的索引索引 mongodb 字段的正确方法是什么?

php - Mikrotik - 使用无限循环的内部登录页面

python - 我的代码正在处理字典列表,就像字符串一样,类型错误: TypeError: string indices must be integers

java - org.apache.struts2.json.JSONException : org. hibernate.LazyInitializationException:未能延迟初始化集合

android - 不使用 Preference 和 SQLite 保存数据

php - Mysql 抛出查询错误但完成查询却很好 - 为什么?

php - 如何在不重新加载页面的情况下保持 session 事件?

php - 在远程服务器上运行 beanstalkd worker