Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

List by first name and not ID WordPress


This is not WP related but it's PHP so I hope someone here can help me :)

I've got a page that lists the staff. Each staff member (teacher) has an ID, but I want the list to be sorted alphabetically by the name.

On the current page at the bottom, you can see that the teacher Ann Kathrine should have been at the top of the site. The current site is here:

The code is here and below: (I've removed the profile images to make the code easier to read)

NOTE: You can't test the code because there's an authorization key that I ofc can't share here.

<?php function executeRESTCall($method, $url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
$header = array();
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: THIS-IS-HIDDEN';
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
return curl_exec($curl);
$baseUrl = '';
$teachersJSONString = executeRESTCall('GET', $baseUrl . 'teachers');
// $getMads = executeRESTCall('GET', '');
// Convert JSON string to Object
$teachers = json_decode($teachersJSONString);
// Use print_r($teachers); to printing all teachers, then you can see what values you have in there
// Loop through Object
foreach($teachers as $key => $value) {
$external_link = "". strval($value->TeacherId) . ".jpg";
// define a variable for the image url with the teacher ID
if (true) {
echo '<tr>';
echo '<td><strong>' . ($value->Name . "\n\n") . ($value->Surname) . '</strong>';
echo '<ul>';
// There might be a better way to do this, but this works :)
// This lists the 'listemedfag' for each teacher
$listemedfag = $value->AvailableClasses;
for ($i = 0; $i < count($listemedfag); $i++)
echo '<li>' . $listemedfag[$i] . '</li> ' . "\n";
echo '</ul>';
echo '<td>Email: <a href="mailto:' . $value->Email . '">' . ($value->Email . '</a>' . "\n\n");
echo '<br>Tlf. ' . ' ' .($value->Mobile . "\n\n");
echo '</td></tr>';

Answers (2)


John Cotton answers:

You probably want to use usort.

$teachers = json_decode($teachersJSONString);
usort ($teachers, function ($a, $b) {
return strcmp( strtolower($a->name), strtolower($b->name) ); // ->name or whatever the property name actually is

// $teachers is now sorted alphabetically.


Reigel Gallarde answers:

something like this, after your json_decode...

usort($teachers, function($a, $b) { //Sort the array using a user defined function
return strtolower($a->Name) > strtolower($b->Name) ? -1 : 1; //Compare the Name or use Surname or concatenate both.. depends on your requirement


Reigel Gallarde comments:

more readings: