9

After much searching I haven't been able to find a good explanation on how to use array_multisort() to case insensitively sort a multidimensional array by one field. I find this to be a very helpful feature when dealing with information from database queries so thought I would share.

0

3 Answers 3

17

I should note this only works in php 5.4+

# Example results from database
$PDOresult = array(
    array('name' => 'Alpha', 'price' => '10'),
    array('name' => 'beta', 'price' => '12'),
    array('name' => 'Gamma', 'price' => '14'),
    array('name' => 'delta', 'price' => '16'),
    array('name' => 'Epsilon', 'price' => '18'),
    array('name' => 'zeta', 'price' => '20'),
    ...
);

# Create array of field to sort by - 'name' in this example
foreach ($PDOresult as $key => $row) {
    $sort_by[$key] = $row['name'];
}

# Sort array - The flags SORT_NATURAL & SORT_FLAG_CASE are required to make the
# sorting case insensitive.
array_multisort($sort_by, SORT_ASC, SORT_NATURAL|SORT_FLAG_CASE, $PDOresult);

# Output
var_dump($PDOresult);

If using php 5.5+ you can skip the foreach() and use array_column() instead. Like so:

$sort_by = array_column($PDOresult, 'name');

I was tempted to edit this into the well written answer: How can I sort arrays and data in PHP? but I didn't want to screw up the formatting so if someone wants to do that and close this, that would be fine with me.

Sign up to request clarification or add additional context in comments.

Comments

5

@damndaewoo

SORT_ASC|SORT_NATURAL|SORT_FLAG_CASE

Will give you in some case :

Warning: array_multisort(): Argument #2 is an unknown sort flag 

As the documentation say here you should use ',' instead of '|' But you CANNOT do the following :

SORT_ASC,SORT_NATURAL,SORT_FLAG_CASE Because you will get an unexpected :

Argument #4 is expected to be an array or sorting flag that has not already been specified

instead you are going to use both technics as follow :

array_multisort($sort_by, SORT_ASC,SORT_NATURAL|SORT_FLAG_CASE, $PDOresult);

1 Comment

I have not struck this warning before and I've been using this method for some time now. I'm guessing it depends on your configuration
1

You could also simply do this:

foreach ($PDOresult as $key => $row) {
    $sort_by[$key] = strtolower($row['name']);
}

array_multisort($sort_by, SORT_ASC, $PDOresult);

No special flags are needed as everything that is sorted by is lower case. If you are worried about UTF-8, use mb_strtolower() instead. This will have the same result as the solution with the special flags, but is in my opinion more intuitive.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.