[PHP] 纯文本查看 复制代码
<?php
//创建数组以及输出数组的三种方式
$temp = array(1,2,3,4,5,6); //定义数组$temp
$temp1 = array(
0=>"zero",
1=>"one",
2=>"two",
3=>"three"
); //定义数组$temp1
$temp2 = array(
name =>"张三",
sex =>"男",
age =>"20"
); //定义数组$temp2
echo $temp[0]; //输出数组
echo "、";
echo $temp[1];
echo "、";
echo $temp[2];
echo "、";
echo $temp[3];
echo "、";
echo $temp[4];
echo "、";
echo $temp[5];
echo "、";
echo $temp[6];
echo "<p>";
for($i=0;$i<count($temp1);$i++) //循环输出数组
echo $temp1[$i].",";
echo "<p>";
echo $temp2[name]; //输出数组
echo "<p>";
echo $temp2[sex];
echo "<p>";
echo $temp2[age];
//计算数组个数
echo "<p>";
echo "数组个数:".count($temp)."个";
//数组排序
echo "<p>降序:";
rsort($temp); //降序
for($i=0;$i<count($temp);$i++) //循环输出数组
echo $temp[$i].",";
echo "<p>升序:";
sort($temp); //升序
for($i=0;$i<count($temp);$i++) //循环输出数组
echo $temp[$i].",";
echo "<p>";
//自定义排序
echo "<p>自定义排序:";
function temprsort($a,$b){
if($a == "zero"){
if($b =="zero" ){
return 0;
}else if($b =="one"){
return 1;
}else if($b =="two"){
return 1;
}else{
return 1;
}
}else if($a == "one"){
if($b =="zero" ){
return -1;
}else if($b =="one"){
return 0;
}else if($b =="two"){
return 1;
}else{
return 1;
}
}else if($a == "two"){
if($b =="zero" ){
return -1;
}else if($b =="one"){
return -1;
}else if($b =="two"){
return 0;
}else{
return 1;
}
}else {
if($b =="zero" ){
return -1;
}else if($b =="one"){
return -1;
}else if($b =="two"){
return -1;
}else{
return 0;
}
}
}
usort($temp1,"temprsort");
for($i=0;$i<count($temp1);$i++) //循环输出数组
echo $temp1[$i]." ";
//移动数组指针
echo "<p>移动数组指针<p>";
echo "指针当前指向:";
echo current($temp1); //打印当前数组元素,以确定指针位置
echo "<p>";
echo "指针后移一位:";
next($temp1); //数组指针后移一位
echo current($temp1); //查看当前数组指针指向
echo "<p>";
echo "指针移动尾部:";
end($temp1); //把数组指针移动的数组尾部
echo current($temp1); //查看是否已到尾部
echo "<p>";
echo "指针前移一位:";
prev($temp1); //把数组指针前移一位
echo current($temp1); //查看指针指向情况
echo "<p>";
echo "指针移动到头部:";
reset($temp1); //把数组指针指向头部
echo current($temp1); //查看是否已到头部
//获取数组当前元素
echo "<p>获取数组当前元素<p>";
echo current($temp1);
//移去数组中重复的值
echo "<p>移去数组中重复的值<p>";
$temp1[4] = "two";
$temp1[5] = "one";
echo "去重前:";
for($i=0;$i<count($temp1);$i++) //循环输出数组
echo $temp1[$i].",";
echo "<p>";
$temp3 = array_unique($temp1);
echo "去重后:";
for($i=0;$i<count($temp3);$i++) //循环输出数组
echo $temp3[$i].",";
echo "<p>";
//计算数组中所有值出现的次数
echo "<p>计算数组中所有值出现的次数<p>";
$new1 = array_count_values($temp1); //使用 array_count_values()进行处理
echo "zero 出现的次数为:";
echo $new1[zero]; //打印 zero 出现的次数
echo "<p>";
echo "one 出现的次数为:";
echo $new1[one]; //打印 one 出现的次数
echo "<p>";
echo "two 出现的次数为:";
echo $new1[two]; //打印 two 出现的次数
?>