在php数组学习摘录部分了解到最基本的php数组的建立和数组元素的显示。需要深入学习下php数组的相关操作。首先接触的就是数组元素的升序、降序的排序问题。
1,快速创建数组的函数range()
比如range()函数可以快速创建从1到9的数字数组:
<?php $numbers=range(1,9); echo $numbers[1]; ?> |
<?php $numbers=range(a,z); foreach ($numbers as $mychrs) echo $mychrs." "; ?> |
<?php $people=array('name','sex','nation','birth'); foreach ($people as $mychrs) echo $mychrs." "; sort($people); echo "<br />---排序后---<br />"; foreach ($people as $mychrs) echo $mychrs." "; ?> |
<?php echo "---按数字升序排序---<br />"; $num2=array('26','3',); sort($num2,sort_numeric); foreach ($num2 as $mychrs) echo $mychrs." "; echo "<br />---按字符升序排序---<br />"; $num3=array('26','3'); sort($num3,sort_string); foreach ($num3 as $mychrs) echo $mychrs." "; ?> |
$num1=range(1,9); rsort($num1); |
$peoples=array('xm'=>'name','xb'=>'sex','mz'=>'nation','cs'=>'birth'); |
<?php $peoples=array('xm'=>'name','xb'=>'sex','mz'=>'nation','cs'=>'birth'); foreach ($peoples as $mychrs) echo $mychrs." "; echo "<br />--按元素值升序排列--<br />"; asort($peoples); foreach ($peoples as $mychrs) echo $mychrs." "; echo "<br />--按关键字升序排列--<br />"; ksort($peoples); foreach ($peoples as $mychrs) echo $mychrs." "; ?> |
<?php $fer=array('cnbruce','cnrose','cnjames','cnanne'); shuffle($fer); foreach ($fer as $mychrs) echo $mychrs." "; ?> |
<?php $fer=array('cnbruce','cnrose','cnjames','cnanne'); foreach ($fer as $mychrs) echo $mychrs." "; $fer=array_reverse($fer); echo "<br />--按原顺序反向--<br />"; foreach ($fer as $mychrs) echo $mychrs." "; ?> |
新闻热点
疑难解答