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

How do you alphabetize a json file in php by an element?

目前,我有这个 json 文件:

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

我使用 php 创建了 table,但我希望能够按公司名称对 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 键对其进行排序是没有意义的,它是父键,请使用内部级别中的键 (price, style, etc..):

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