首页 > 解决方案 > 对 PHP 中“复杂”API 的 json 结果进行排序

问题描述

我有一个我无法解决的问题。我要求 API 在选择框中获取字段,一切正常……但我想让它们按字母顺序排序。

我查看了usort函数,但由于我认为的 json 架构,它不起作用。我需要更多知识才能知道如何做到这一点,但我找不到答案。非常感谢。

$urlsta = "https://hubeau.eaufrance.fr/api/v1/hydrometrie/referentiel/stations?code_departement=71&en_service=true&format=json&size=50";
$raw = file_get_contents($urlsta);
$json = json_decode($raw,true);
usort($json['data'], function($a, $b) { return $a->libelle_commune > $b->libelle_commune ? -1 : 1; });                                                            
foreach($json['data'] as $ligne) {
  echo "<option value='".$ligne['code_station']."' ";
  echo ">".$ligne['libelle_commune']." - ".$ligne['libelle_cours_eau']."</option>";
}

标签: phpjson

解决方案


在我的猜测中。json['data']是一个数组,所以你不要使用$a->libelle_commune

我的代码

usort($json['data'], function($a, $b) { return $a['libelle_commune'] < $b['libelle_commune'] ? -1 : 1; });

排序 abc... 与<和 ...cba 与>


推荐阅读