Heim  >  Artikel  >  Backend-Entwicklung  >  PHP数组排序_PHP教程

PHP数组排序_PHP教程

WBOY
WBOYOriginal
2016-07-13 17:35:25755Durchsuche

PHP数组排序实际上就是将PHP数组进行排序,在本文中也就是对数据库查询出来的结果集进行排序。数据库查询结果有时候不能直接使用,比如mysql等用in语句出来的结果,因此需要对结果进行某种方式的排序。这时候就需要进行PHP数组排序了。对数据库结果进行排序请看下面的示例:

本例中data 数组中的每个单元表示一个表中的一行。这是典型的数据库存放数组数据的方式。
例子中的数据如下:
volume | edition
-------+--------
    67 |       2
    86 |       1
    85 |       6
    98 |       2
    86 |       6
    67 |       7

数据全都存放在名为 data 的数组中。这通常是通过循环从数据库取得的结果,例如 mysql_fetch_assoc()(实际上这个函数你可以和mysql_fetch_assoc()函数看成一样,具体的差别你可以看PHP的手册里面关于key的差别)。
$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

实际上真正在排序的时候还有很多方法可以使用,比如php的array数组自带的 arsort(),asort(),ksort(),krsort(),natsort(),natcasesort(),rsort(),usort(),array_multisort() 和 uksort()。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/508331.htmlTechArticlePHP数组排序实际上就是将PHP数组进行排序,在本文中也就是对数据库查询出来的结果集进行排序。数据库查询结果有时候不能直接使用,比...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn