Radim Kleinpeter
Radim Kleinpeter

Reputation: 108

How to sort array by subarray key and value

Hello everybody :) this is my first question, so I hope for answer :) I've got an array of arrays like this :

Array(
    [] => Array ([category] => 3 )
    [] => Array ([price] => 5 )
    [] => Array ([rating] => 1 )
    [] => Array ([price] => 3 )
    [] => Array ([category] => 1 )
    [] => Array ([category] => 2 )
    )
)

Question : How could I sort it for ex. alphanumerically by subarray key and subarray value, so that it is converted like the one following?

Array(
    [] => Array ([category] => 1 )
    [] => Array ([category] => 2 )
    [] => Array ([category] => 3 )
    [] => Array ([price] => 3 )
    [] => Array ([price] => 5 )
    [] => Array ([rating] => 1 )
)

Upvotes: 0

Views: 188

Answers (1)

georg
georg

Reputation: 215009

You're looking for array_multisort:

$x = Array(
    Array ("category" => 3 ),
    Array ("price" => 5 ),
    Array ("rating" => 1 ),
    Array ("price" => 3 ),
    Array ("category" => 1 ),
    Array ("category" => 2 ),

);

array_multisort(
    array_map('key', $x), 
    array_map('current', $x), 
    $x);

print_r($x);

Upvotes: 2

Related Questions