javascript - 如何在 php 中按元素按字母顺序排列 json 文件?

标签 javascript php arrays json usort

目前,我有这个 json 文件:

{"root":[
       {
          "companyname":"Zcompany",
          "style":"Dstyle",
          "price":"$ 99.99"
       },
       {
          "companyname":"Scompany",
          "style":"Gstyle",
          "price":"$ 129.99"
       },
       {
          "companyname":"Fcompany",
          "style":"Estyle",
          "price":"$ 19.99"
       }
    ]
}

我使用 php 创建了一个表,但我希望能够按公司名称按字母顺序排列 json 文件。

我就是无法让 usort 工作。我很确定这是因为我对我拥有的 json 类型使用了错误的 usort。

但是,我似乎无法弄清楚我做错了什么。

<?php
//read json file
$file = 'root.json';
$filedata = file_get_contents($file);
$root = json_decode($filedata,true);

function build_sorter($key) {
  return function ($a, $b) use ($key) {
      return strnatcmp($a[$key], $b[$key]);
  };
}

usort($root, build_sorter('root'));

foreach($root['root'] as $p) {
  //prints table from the json file
  echo '<tr><br>
    <td>'.$p['companyname'].'</td>'.
    '<td>'.$p['style'].'</td>'.
    '<td>'.$p['price'].'</td>'.
    '</tr>';
  ;
}
?>

当我运行上面的代码时,出现错误

Warning: Invalid argument supplied for foreach() in on line 14// the line that starts the foreach.

Undefined index: root in on line 14// same line that starts the foreach

最佳答案

尝试通过 root 键(它的父键)对其进行排序是没有意义的,请使用内部级别中的键(价格、样式等......):

usort($root['root'], build_sorter('price'));

关于javascript - 如何在 php 中按元素按字母顺序排列 json 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29291410/

相关文章:

php - 从 Android 应用程序连接和更新 php 服务器

javascript - 在 react 中映射数组时处理点击

php - Laravel 目标类 [App\Http\Controllers\App\Http\Controllers\ApiController] 不存在

php - 从 mysql 读取和使用十进制数据类型时的数学问题

javascript - 如何比较两个数组是否相等?

javascript - JS如何展平嵌套数组

java - 数组元素 :array-name in Java

javascript - 未捕获的语法错误 : Unexpected token ILLEGAL issue with markdown to HTML converter

javascript - 调用 window.location.assign 后,chrome/firefox 之间的网页渲染行为不同

javascript - 如何清除调用自身的函数内部的间隔javascript