0

I have a problem I can't solve. I ask an API to get fields in a select box and everything works well... but I would like to have them sorted alphabetical.

I looked on usort function but it doesn't work because of the json architecture I think. I need more knowledge to know how to do that and I can't find that answer. Thanks a lot.

$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>";
}
JoSSte
  • 2,210
  • 5
  • 25
  • 40

1 Answers1

0

In my guess. json['data'] is a array so you dont use $a->libelle_commune

My code

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

sort abc... with < and ...cba with >

Mai Truong
  • 96
  • 6
  • 1
    If you're using PHP 7 you can even even use the so called spaceship operator: `return $a['libelle_commune'] <=> $b['libelle_commune'];`. This sorts in the `abc` order. If you want that reversed, switch the `$a` and the `$b`. More info on that [over here](https://stackoverflow.com/questions/30365346/what-is-the-spaceship-operator-in-php-7) – Douwe de Haan Nov 05 '20 at 08:50