数组分类
- 索引数组
- 关联数组
数组遍历
- 传值遍历
- 传址遍历
数组函数
- 指针操作函数
- current($array) 当前位置的内容
- key($array) 当前位置的键值
- next($array) 指针移动到下一个单元
- prev($array) 指针移动到上一个单元
- reset($array) 指针移动到第一个单元
- end($array) 指针移动到最后一个单元
- 单元函数操作
- array_pop($array) 删除数组中的最后一个元素
<?php
$a=array("red","green","blue");
array_pop($a);
print_r($a);
?>
Array ( [0] => red [1] => green )
- array_push($array,$ele,$ele2) 数组尾部插N个元素
<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
- array_shift($array) 删除数组中的第一个元素(red),并返回被删除元素的值
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_shift($a);
print_r ($a);
?>
redArray ( [b] => green [c] => blue )
- array_unshift($array,$ele) 把元素插入数组中
<?php
$a=array("a"=>"red","b"=>"green");
array_unshift($a,"blue");
print_r($a);
?>
Array ( [0] => blue [a] => red [b] => green )
- array_slice($array,2) 从数组的第三个元素开始取出,并返回数组中的其余元素
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
Array ( [0] => blue [1] => yellow [2] => brown )
- array_splice($array,2,$要替换的元素) 把数组中的一部分去掉并用其它值取代,2后面的元素都去掉
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,0,2,$a2);
print_r($a1);
?>
Array ( [0] => purple [1] => orange [c] => blue [d] => yellow )
- array_map('two',$array) 可以对数组中的每一个元素,按照two函数的规则操作返回一个新的数组
<?php
function myfunction($v)
{
return($v*$v);
}
$a=array(1,2,3,4,5);
print_r(array_map("myfunction",$a));
?>
Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )
- compact('变量名字','变量名字') 把多个变量的名字和内容,合成一个数组
<?php
$firstname = "Bill";
$lastname = "Gates";
$age = "60";
$result = compact("firstname", "lastname", "age");
print_r($result);
?>
Array ( [firstname] => Bill [lastname] => Gates [age] => 60 )
- extract($array) 把数组中的内容分解成一个一个变量
<?php
$a = "Original";
$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($my_array);
echo "\$a = $a; \$b = $b; \$c = $c";
?>
$a = Cat; $b = Dog; $c = Horse
- array_merge($array,$array) 合成多个数组
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
- array_chunk($array,2,true) 把数组分割为带有两个元素的数组
<?php
$cars=array("Volvo","BMW","Toyota","Honda","Mercedes","Opel");
print_r(array_chunk($cars,2));
?>
Array ( [0] => Array ( [0] => Volvo [1] => BMW ) [1] => Array ( [0] => Toyota [1] => Honda ) [2] => Array ( [0] => Mercedes [1] => Opel ) )
排序
- sort 排序
- asort 下标保留
- ksort
- usort
- rsort
- shuffle 乱序