Home >php教程 >php手册 >PHP中常用数组处理方法实例分析

PHP中常用数组处理方法实例分析

WBOY
WBOYOriginal
2016-06-13 12:27:052266browse

1.array_shift()将数组的第一个单元移出再返回,这对有时候数组的第一个单元要单独处理很方便。

复制代码 代码如下:



$tmparray = array("1", "2", "3", "4");
$tmparray = array_shift ($tmparray);
print_r($tmparray);
?>



2.array_chunk() 将一个数组分割成多个数组 ,后面参数控制数组单元数目。

复制代码 代码如下:



$tmparray = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($tmparray, 2));
?>


这个函数在有些循环的地方很好用,比如我要把取得的数据放成N排,M列。要是我们直接循环肯定不行,当然用嵌套循环可以实现,但是太麻烦,要是先用 array_chunk()这个函数先处理再返回新的数组,就很方便了。
3.array_push()将传入的值压入array的末尾。

复制代码 代码如下:



$tmparray = array ("a", "b");
array_push ($tmparray, "c", "d");
print_r($tmparray);//Array([0] => a[1] =>b[2] =>c[3] =>d)
?>


4.array_unshift() 将传入的单元整体插入到数组中

复制代码 代码如下:


$tmparray= array ("a", "b");
$resarray = array_unshift ($tmparray, "c", "d");
print_r($resarray )//Array([0] => a[1] =>b[2] =>c[3] =>d)
?>


5.array_unique对数组去重,并返回一个新的数组

复制代码 代码如下:



$tmparray = ("a" => "a","b" => "b","c" => "c","d" => "b");
$resarray = array_unique($tmparray);//("a" => "a","b" => "b","c" => "c");
?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn