php一维数组排序与多维数组排序
先看一维数据排序的实例asort()函数和ksort()函数,实例代码如下:
- <?php
- //asort()函数以数组的值升序为准
- $mix = array("Clalei"=>10,"Bill"=>50,"Aala"=>100);
- asort($mix);
- print_r($mix);
- //ksort()函数以数组的关键字升序为准
- $mix = array("Clalei"=>100,"Bill"=>50,"Aala"=>10);
- ksort($mix);
- print_r($mix);
- ?>
一维数据排序二,sort()函数,可将数组按字母或是数字的升序(从低到高)来进行排序,实例代码如下:
- <?php
- $name = array("Clalei","Bill","Aala");
- //开源代码phpfensi.com
- sort($name);
- for($i=0;$i<3;$i++){
- echo $name[$i];
- }
- echo "<br />";
- $price = array(100,50,10);
- sort($price);
- for($i=0;$i<3;$i++){
- echo $price[$i]." | ";
- }
- ?>
好了现在来看看二维数据库排序实例代码:
- $data[] = array('volume' => 67, 'edition' => 2);
- $data[] = array('volume' => 86, 'edition' => 1);
- $data[] = array('volume' => 85, 'edition' => 6);
- $data[] = array('volume' => 98, 'edition' => 2);
- $data[] = array('volume' => 86, 'edition' => 6);
- $data[] = array('volume' => 67, 'edition' => 7);
本例中将把 volume 降序排列,把 edition 升序排列,现在有了包含有行的数组,但是 array_multisort() 需要一个包含列的数组,因此用以下代码来取得列,然后排序,实例代码如下:
- // 取得列的列表
- foreach ($data as $key => $row) {
- $volume[$key] = $row['volume'];
- $edition[$key] = $row['edition'];
- }
- // 将数据根据 volume 降序排列,根据 edition 升序排列
- // 把 $data 作为最后一个参数,以通用键排序
- array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
数据集合现在排好序了,结果如下:
- volume | edition
- -------+--------
- 98 | 2
- 86 | 1
- 86 | 6
- 85 | 6
- 67 | 2
- 67 | 7
二维数组排序三
array_multisort() 对二维数组进行排序,数组$roughData,我们打算按照accurancy排序,代码如下:
- Array( [0] => Array ( [username] => 10yl [accuracy] => 0.00 ) [1] => Array ( [username] => 11yl [accuracy] => 1.00 ) [2] => Array ( [username] => 12yl [accuracy] => 0.00 ) [3] => Array ( [username] => 13yl [accuracy] => 1.00 ))
方法:
(1):提取accuracy列数组
foreach ($roughData as $key => $row) {
$usernames[$key] = $row['username'];
$accuracy[$key] = $row['accuracy'];
}
(2):进行排序
array_multisort($accuracy, SORT_ASC,$roughData);
当print_r($roughData);后我们将得到一个按accuracy升序排序的二维数组,再来看个简单实例用二维数组排序方法,实例代码如下:
- <?php
- $array[] = array("age"=>20,"name"=>"li");
- $array[] = array("age"=>21,"name"=>"ai");
- $array[] = array("age"=>20,"name"=>"ci");
- $array[] = array("age"=>22,"name"=>"di");
- foreach ($array as $key=>$value){
- $age[$key] = $value['age'];
- $name[$key] = $value['name'];
- }
- array_multisort($age,SORT_NUMERIC,SORT_DESC,$name,SORT_STRING,SORT_ASC,$array);
- print_r($array);
- ?>