Home > Backend Development > PHP Tutorial > PHP中sort、asort与ksort区别用法详解

PHP中sort、asort与ksort区别用法详解

WBOY
Release: 2016-06-20 13:02:37
Original
2343 people have browsed it

PHP中sort、asort与ksort对数组的排序方法异同点:

sort只依据值从小到大排序,键值不参与排序

asort依据值排序,键值参与排序

ksort依据键值排序,值参与排序

 

sort只依据值从小到大排序,键值不参与排序。例

 <?php

   $arr=array("a"=>"d","d"=>"c","b"=>"a");

   sort($arr);

   var_dump($arr);

 ?>
Copy after login

结果

array(3) { [0]=> string(1) "a" [1]=> string(1) "c" [2]=> string(1) "d" }

asort依据值进行排序,键值参与排序

 <?php

   $arr=array("a"=>"d","d"=>"c","b"=>"a");

   asort($arr);

   var_dump($arr);

 ?>
Copy after login

结果

array(3) { ["b"]=> string(1) "a" ["d"]=> string(1) "c" ["a"]=> string(1) "d" }

ksort依据键值进行排序,值参与排序

 <?php

   $arr=array("a"=>"d","d"=>"c","b"=>"a");

   ksort($arr);

   var_dump($arr);

 ?>
Copy after login

结果

array(3) { ["a"]=> string(1) "d" ["b"]=> string(1) "a" ["d"]=> string(1) "c" }


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template