Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case Insensitively Sort a Multidimensional PHP Array using array_multisort()

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.

like image 272
damndaewoo Avatar asked Nov 26 '14 04:11

damndaewoo


2 Answers

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.

like image 191
damndaewoo Avatar answered Sep 21 '22 15:09

damndaewoo


@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);

like image 21
Apex Avatar answered Sep 22 '22 15:09

Apex