作者:丶希_ | 来源:互联网 | 2014-06-17 17:22
一般数组中的各元素均以字符或数字表现的,所以可对数组元素进行升序排列,该功能函数为sort(),比如:<?php$peoplearray(&39;name&39;,&39
一般数组中的各元素均以字符或数字表现的,所以可对数组元素进行升序排列,该功能函数为sort(),比如:
- $people=array(&#39;name&#39;,&#39;sex&#39;,&#39;nation&#39;,&#39;birth&#39;);
- foreach ($people as $mychrs)
- echo $mychrs." ";
- sort($people);
- echo "
---排序后---
";
- foreach ($people as $mychrs)
- echo $mychrs." ";
- ?>
升序排序后的数组元素显示为 birth name nation sex,当然,sort()函数是区分字母大小写的(字母从大到小的顺序是:a…z…a…z),sort()函数还具有第二参数,用来说明升序的规则是用来比较数字还是字符串的:
- echo "---按数字升序排序---
";
- $num2=array(&#39;26&#39;,&#39;3&#39;,);
- sort($num2,sort_numeric);
- foreach ($num2 as $mychrs)
- echo $mychrs." ";
- echo "
---按字符升序排序---
";
- $num3=array(&#39;26&#39;,&#39;3&#39;);
- sort($num3,sort_string);
- foreach ($num3 as $mychrs)
- echo $mychrs." ";
- ?>
php中关联数组的排序:
php除了支持数字索引数组以外,还支持相关数组,比如如下数组就是一个相关(关联)数组:
$peoples=array(&#39;xm&#39;=>&#39;name&#39;,&#39;xb&#39;=>&#39;sex&#39;,&#39;mz&#39;=>&#39;nation&#39;,&#39;cs&#39;=>&#39;birth&#39;);
使用sort($peoples)默认即是按照元素定义值的升序排序,在关联数组中可使用asort()函数表示,关联数组中最主要的则是可按照关键字(如xm、xb、mz等)的升序排序,该方法是用函数ksort()函数.
- $peoples=array(&#39;xm&#39;=>&#39;name&#39;,&#39;xb&#39;=>&#39;sex&#39;,&#39;mz&#39;=>&#39;nation&#39;,&#39;cs&#39;=>&#39;birth&#39;);
- foreach ($peoples as $mychrs)
- echo $mychrs." ";
- echo "
--按元素值升序排列--
";
- asort($peoples);
- foreach ($peoples as $mychrs)
- echo $mychrs." ";
- echo "
--按关键字升序排列--
";
- ksort($peoples);
- foreach ($peoples as $mychrs)
- echo $mychrs." ";
- ?>