Question

Possible Duplicate:
Sort multidimensional array by multiple keys

I want know how I can usort an array of arrays by differents data types. For instance, I have this data:

priority | title
2          B
3          C
2          A
1          A
3          D

I need make a "double-sort" (like SQL priority ASC, title ASC) to get it:

priority | title
1          A
2          A      
2          B
3          C
3          D

On really, I need do it with too many values, but I need only the basis. But to enjoy and not risk a different logic, my real problem is to organize like: int priority ASC, string method ASC, string prefix ASC, int index ASC.

I have tried somethings, but I couln't do works. :(

Was it helpful?

Solution

Based on: PHP.net:multisort()

As you have stated in your question, this is just the basics of how it can be done. To make the whole thing more dynamic, you would need a way to pass the sorting choices into a function that then uses them in the foreach to control which sorting arrays are used...

<?php
//Build example data
$data = array();
$data[] = array('priority'=>2,'title'=>'B');
$data[] = array('priority'=>3,'title'=>'C');
$data[] = array('priority'=>2,'title'=>'A');
$data[] = array('priority'=>1,'title'=>'A');
$data[] = array('priority'=>3,'title'=>'D');

foreach ($data as $key => $row) {
    $priority[$key]  = $row['priority'];
    $title[$key] = $row['title'];
}

array_multisort($priority, SORT_ASC, $title, SORT_ASC, $data);

print_r($data);
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top