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.
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:
Example of using the "usort" function to sort an array by a specific value of a subarray in PHP
<?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);
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
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.