PHP的数组声明基本语法:
$arr=array("",,,,,,,,,,,,,);
$arr=array(key==>元素的值,key2==>元素的值2);
这种方法是定义索引,索引可以是字符串或者数字,如果省略了索引,会自动从0开始的整数索引。
如果索引是整数,则下一个产生的索引值是当前最大索引值+1.如果定义了两个完全的索引,后面的定义的索引值会覆盖前面的整数。
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
数组里边存了一个数组,这种数组称之为二维数组
<?php
$many=array(
"var"==>array("a"==>"apper","b"==>"酷似神仙","c"==>"hello php"),
"doli"==>array("one"==>"第一位","two"==>"第二位","three"==>"第三位"),
"hold"==>array("first",3,4=>"fourth")
);
$contact=array(1,"高某","A公司","北京市","(010)1231546","gao@php.com");
echo '<table border="0px" width="600px" align="center">';
echo '<caption><h1>联系人列表</h1></caption>';
echo '<tr><td>编号</td>
<td>姓名</td>
<td>公司</td>
<td>地址</td>
<td>电话</td>
<td>EMAIL</td>
</tr>';
echo '<tr>';
for($i=0;$i<count($contact);$i++){
echo '<td>'.$contact[$i].'</td>';
}
echo '</tr>';
echo '</table>';
二维数组的遍历
$contact=array(array(1,"高某","A公司","北京市","(010)1231546","gao@php.com"),
array(2,"趟某","A公司","北京市","(010)1231546","gao@php.com"),
array(3,"证某","A公司","北京市","(010)1231546","gao@php.com"),
array(4,"云某","A公司","北京市","(010)1231546","gao@php.com"),
array(5,"飞某","A公司","北京市","(010)1231546","gao@php.com")
);
echo '<table border="0px" width="600px" align="center" bgcolor=#dddddd>';
echo '<caption><h1>联系人列表</h1></caption>';
echo '<tr bgcolor="green"><td>编号</td>
<td>姓名</td>
<td>公司</td>
<td>地址</td>
<td>电话</td>
<td>EMAIL</td>
</tr>';
echo count($contact);
for($rows=0;$rows<count($contact);$rows++){
echo '<tr>';
for($cols=0;$cols<count($contact[$rows]);$cols++){
echo '<td>'.$contact[$rows][$cols].'</td>';
}
echo '</tr>';
}
echo '</table>';
?>
自动索引:
<?php
$Ahui=array(1,1,1,4,,4=>34,8,7=>64);
echo $Ahui;
?>
结果:
Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 4 [4] => 8 [7] => 64
对于PHP的数组来说,数组的类型没有做固定的限制,可以是字符串,可以是浮点数,或者是布尔值都可以,如果数组运算比较时候,会自动的进行转换。
二分查找
使用二分查找的数组必须是个有序数组。
二分查找:抽取数组中间的数跟要查找的数做比较,如果大于了中间的数,则往右边查找,找出他的下标。
如果小于中间的数,则往左边查找,找出他的下标。
如下代码:
<?php
function binaryserch(&$arr,$var,$leftindex,$rightindex){
if($leftindex>$rightindex){
echo "没有这个数";
break;
}
$midindex=round(($leftindex+$rightindex)/2)+1;
if($var>$arr[$midindex]){
binaryserch($arr,$var,$midindex+1,$rightindex);
}elseif($var<$arr[$midindex]){
binaryserch($arr,$var,$leftindex,$midindex-1);
}else{
echo "下标已经找到".$midindex;
}
}
$arr=array(10,15,90,91,96);
binaryserch($arr,91,0,count($arr));
?>
顺序查找:
顺序查找即,挨着顺序一个个的与要查找的数作比较,找出这个数。
<?php
$Ahui=array(1,1,1,4,34,4=>8,7=>64);
function search($arr,$finval){
for($i=0;$i<count($arr);$i++){
if($finval==$arr[$i]){
echo $finval;
echo "这正是你想要找的值,下标=".$i;
}
}
}
search($Ahui,8);
print_r($Ahui);
?>