1, "name" => "Boney M", "rating" => 3), ar">
当前位置:Gxlcms > PHP教程 > PHP函数array_multisort()实现多维数组排序的示例讲解_PHP教程

PHP函数array_multisort()实现多维数组排序的示例讲解_PHP教程

时间:2021-07-01 10:21:17 帮助过:32人阅读

对于Listing J示例为我们具体说明了PHP函数array_multisort()的工作方式:

  1. php
  2. $data = array(array("id" => 1, "name" => "Boney M", "rating" => 3),
  3. array("id" => 2, "name" => "Take That", "rating" => 1),
  4. array("id" => 3, "name" => "The Killers", "rating" => 4),
  5. array("id" => 4, "name" => "Lusain", "rating" => 3),
  6. ); foreach ($data as $key => $value) {
  7. $name[$key] = $value['name'];
  8. $rating[$key] = $value['rating'];
  9. }
  10. array_multisort($rating, $name, $data); print_r($data);
  11. ?>

这里,我们在$data数组中模拟了一个行和列数组。然后,我使用PHP函数array_multisort()对数据集合进行重排,首先是根据rating进行排序,然后,如果rating相等的话,再根据name排序。它的输出结果如下:

Array ([0] => Array

(

[id] => 2

[name] => Take That

[rating] => 1

) [1] => Array

(

[id] => 1

[name] => Boney M

[rating] => 3

)

[2] => Array

(

[id] => 4

[name] => Lusain

[rating] => 3

)

[3] => Array

(

[id] => 3

[name] => The Killers

[rating] => 4

)

)

PHP函数array_multisort()是PHP中最有用的函数之一,它有非常广泛的应用范围。另外,就如你在例子中所看到的,它能对多个不相关的数组进行排序,也可以使用其中的一个元素作为下次排序的基础,还可以对数据库结果集进行排序。


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/446344.htmlTechArticle对于 Listing J示例为我们具体说明了PHP函数array_multisort()的工作方式: ? php $ data = array (array("id"= 1,"name"= "BoneyM","rating"= 3), array("id"= 2,"name"=...

人气教程排行