PHP sort array alphabetically using a subarray value
In PHP, you can use the "usort" function to sort an array by a specific value of a subarray. Here is an example of how you would sort an array of people by their last names alphabetically:
<?php
$people = [
['first_name' => 'John', 'last_name' => 'Doe'],
['first_name' => 'Jane', 'last_name' => 'Smith'],
['first_name' => 'Bob', 'last_name' => 'Johnson']
];
usort($people, function ($a, $b) {
return strcmp($a['last_name'], $b['last_name']);
});
print_r($people);
Watch a video course
Python - The Practical Guide
This will output:
Array ( [0] => Array ( [first_name] => Bob [last_name] => Johnson ) [1] => Array ( [first_name] => John [last_name] => Doe ) [2] => Array ( [first_name] => Jane [last_name] => Smith ) )
You can also use "array_multisort" to sort by multiple subarray values.