Link to home
Start Free TrialLog in
Avatar of Web IT
Web IT

asked on

sort by secondary array

I have this array .
how can I sort by first name in php (current;y it's sorted by id) ?

 
[1611] => Array
        (
            [first_name] => Daniel
        )

    [1610] => Array
        (
            [first_name] => Batman
        )

    [1609] => Array
        (
            [first_name] => Abraham

        )

Open in new window

Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

You use the usort() function combined with either the strcmp() or strcasecmp() function (depending on what you want the results to be)

If you use the strcmp() function with the following
<?php
$friends = [
  ['name' => 'Zelda'],
  ['name' => 'admam'], 
  ['name' => 'quinton'],
  ['name' => 'charlie'],
  ['name' => 'xenia']
];
usort($friends, function($a, $b) {
	return strcmp($a['name'], $b['name']);
});
print_r($x);

Open in new window

You will get the following
Array
(
    [0] => Array
        (
            [name] => Zelda
        )

    [1] => Array
        (
            [name] => admam
        )

    [2] => Array
        (
            [name] => charlie
        )

    [3] => Array
        (
            [name] => quinton
        )

    [4] => Array
        (
            [name] => xenia
        )

)

Open in new window

if you use strcasecmp() you get
Array
(
    [0] => Array
        (
            [name] => admam
        )

    [1] => Array
        (
            [name] => charlie
        )

    [2] => Array
        (
            [name] => quinton
        )

    [3] => Array
        (
            [name] => xenia
        )

    [4] => Array
        (
            [name] => Zelda
        )

)

Open in new window

This is because lexicographically capital 'Z' comes before lower case 'a'.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.