PHP array_mulitsort

1.函数的作用:对多维数组进行排序

2.函数的例子:

例子一:

 1 <?php
 2 // http://php.net/manual/zh/function.array-multisort.php
 3 $multiArray = Array(
 4     Array("id" => 1, "name" => "Defg"),
 5     Array("id" => 2, "name" => "Abcd"),
 6     Array("id" => 3, "name" => "Bcde"),
 7     Array("id" => 4, "name" => "Cdef"));
 8 $tmp = Array();
 9 foreach($multiArray as &$ma)
10     $tmp[] = &$ma["name"];
11 array_multisort($tmp, $multiArray);
12 foreach($multiArray as &$ma)
13     echo $ma["name"]."<br/>";
14                
15 /* Outputs
16     Abcd
17     Bcde
18     Cdef
19     Defg
20 */ 
 1 <?php
 2 // http://php.net/manual/zh/function.array-multisort.php
 3 $multiArray = Array(
 4     Array("id" => 1, "name" => "Defg"),
 5     Array("id" => 2, "name" => "Abcd"),
 6     Array("id" => 3, "name" => "Bcde"),
 7     Array("id" => 4, "name" => "Cdef"));
 8 $tmp = Array();
 9 foreach($multiArray as &$ma)
10     $tmp[] = &$ma["name"];
11 array_multisort($tmp, $multiArray);
12 foreach($multiArray as &$ma)
13     echo $ma["name"]."<br/>";
14                
15 /* Outputs
16     Abcd
17     Bcde
18     Cdef
19     Defg
20 */ 

例子二:

 1 // http://php.net/manual/zh/function.array-multisort.php
 2 function array_msort($array, $cols)
 3 {
 4     $colarr = array();
 5     foreach ($cols as $col => $order) {
 6         $colarr[$col] = array();
 7         foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
 8     }
 9     $eval = 'array_multisort(';
10     foreach ($cols as $col => $order) {
11         $eval .= '$colarr[\''.$col.'\'],'.$order.',';
12     }
13     $eval = substr($eval,0,-1).');';
14     eval($eval);
15     $ret = array();
16     foreach ($colarr as $col => $arr) {
17         foreach ($arr as $k => $v) {
18             $k = substr($k,1);
19             if (!isset($ret[$k])) $ret[$k] = $array[$k];
20             $ret[$k][$col] = $array[$k][$col];
21         }
22     }
23     return $ret;
24 
25 }

 

posted @ 2017-05-08 16:45  GoodByeZ  阅读(317)  评论(0编辑  收藏  举报