<?php
$a=array("red", "green", "blue", "yellow");
count ($a); //得到4
array_splice($a,1,1); //删除第二个元素
count ($a); //得到3
echo $a[2]; //得到yellow
echo $a[1]; //得到blue
?>
实例三:array_unique删除数组中的重复值:
复制代码 代码如下:
<?php
$a=array("red", "green", "blue", "yellow","blue","green");
$result = array_unique($a);
print_r($result);
?>
运行结果:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
实例四:array_merge、array_merge_recursive合并数组
复制代码 代码如下:
<?php
$array1 = array("r"=>"red",1,2,3,4);
$array2 = array("b"=>"blue",4=>5,6,7,8,9);
$array3 = array("r"=>"read",4=>10,2=>11);
$array4 = array(
array(4=>10),
array(7=>13)
);
$array5 = array(
array(4=>11),
array(6=>12)
);
$result = array_merge($array1,$array2,$array3,$array4,$array5);
echo "<pre>";
print_r($result);
echo "</pre>";
$result = array_merge_recursive($array1,$array2,$array3,$array4,$array5);
echo "<pre>";
print_r ($result);
echo "</pre>";
?>
运行结果:
复制代码 代码如下:
Array
(
[r] => read
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[b] => blue
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
[10] => 11
[11] => Array
(
[4] => 10
)
[12] => Array
(
[7] => 13
)
[13] => Array
(
[4] => 11
)
[14] => Array
(
[6] => 12
)
)
Array
(
[r] => Array
(
[0] => red
[1] => read
)
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[b] => blue
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
[10] => 11
[11] => Array
(
[4] => 10
)
[12] => Array
(
[7] => 13
)
[13] => Array
(
[4] => 11
)
[14] => Array
(
[6] => 12
)
)
注:1. array_merge的键名是数字的将重新建立索引;遇到相同的字符串键名时,后面的将覆盖前面的。 2. array_merge_recursive函数的作用是将相同字符串的键名单元整合成一个数组。
6. 数组的键值和值操作
实例一:in_array()检测数组中是否有某个值存在
复制代码 代码如下:
<?php
$array = range(0,9);
if(in_array(9,$array)){
echo "数组中存在";
}
?>
运行结果:数组中存在
实例二:key()取得数组当前的键名:
复制代码 代码如下:
<?php
$array = range(0,9);
$num = rand(0,8);
while($num--)
next($array);
$key = key($array);
echo $key;
?>
此实例结果为动态结果,范围(0-8),不做结果演示。
实例三:list()函数把数组中的值赋给指定变量:
复制代码 代码如下:
<?PHP
$staff = array(
array("姓名","性别","年龄"),
array("小张","男",24),
array("小王","女",25),
array("小李","男",23)
);
echo "<table border=2>";
while(list($keys,$value) = each($staff)){
list($name,$sex,$age) = $value;
echo "<tr><td>$name</td><td>$sex</td><td>$age</td></tr>";
}
echo "</table>";
?>
实例四:array_flip()交换数组的键值和值:
复制代码 代码如下:
<?PHP
$array = array("red","blue","yellow","Black");
print_r($array);
echo "<br />";
$array = array_flip($array);
print_r($array);
?>
运行结果:
Array ( [0] => red [1] => blue [2] => yellow [3] => Black )
Array ( [red] => 0 [blue] => 1 [yellow] => 2 [Black] => 3 )
复制代码 代码如下:
<?PHP
$array = array("red","blue","yellow","Black");
$result = array_keys($array);
print_r($result);
echo "<br />";
$result = array_values($array);
print_r($result);
?>
运行结果:
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 )
Array ( [0] => red [1] => blue [2] => yellow [3] => Black )
实例六:array_search()搜索数值:
复制代码 代码如下: