开发者

usort: how I can sort by multiple data types? [duplicate]

开发者 https://www.devze.com 2023-04-13 08:23 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Sort multidimensional array by multiple keys
This question already has answers here: Closed 11 years ago.

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 n开发者_开发百科eed 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. :(


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);
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消