使用array() 函数创建数组
php的三种数组类型
//索引从0开始 $animal=array("Dog","Cat","Tiger"); $animal2=array(); $animal2[0]="Lion"; $animal2[1]="Monkey"; //I like Dog,Cat and Tiger.I hate Monkey echo "I like ".$animal[0].",".$animal[1]." and ".$animal[2].".I hate ".$animal2[1]; echo "<br>"; //获取长度 echo count($animal); //3 echo "<br>"; //遍历数组 for($i=0;$i<count($animal);$i++){ echo $animal[$i]; echo "<br>"; }
键 => 值
//关联数组 $student=array("DogFly"=>"10","未成年"=>"15","网购用"=>"21"); $goods['mushroom']="5"; $goods['eggplant']="6"; $goods['cucumber']="9"; //输出,这边都要用单引号 echo "DogFly is ".$student['DogFly']."<br>"; echo "未成年 is ".$student['未成年']."<br>"; echo "网购用 is {$student['网购用']}"; echo "<br>"; //遍历 foreach($goods as $i=>$i_value){ echo "vegetable=".$i.",amount=".$i_value; echo "<br>"; }
$a=array(65,45,78,12,32); $animal=array("Dog","Cat","Tiger"); sort($a); sort($animal); for($i=0;$i<count($a);$i++){ echo $a[$i]." "; //升序 } echo "<br>"; for($i=0;$i<count($animal);$i++){ echo "$animal[$i]"." "; //按字母排 } echo "<br>"; rsort($a); //降序 for($i=0;$i<count($a);$i++){ echo $a[$i]." "; }
$student=array("DogFly"=>"16","未成年"=>"15","网购用"=>"21"); asort($student); foreach($student as $key=>&$value){ //根据value的值升序排 echo $key." : ".$value; echo "<br>"; } echo "<br>"; ksort($student); //根据key的值排序 foreach($student as $key=>&$value){ echo $key." : ".$value; echo "<br>"; } arsort($student); //根据value降序排 krsort($student); //根据key降序排