目前,我有这个 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/