php 操作数组 (合并,拆分,追加,查找,删除等)

 

0.输出数组

bool print_r ( mixed expression [, bool return] )

如果给出的是 string、integer 或 float,将打印变量值本身。如果给出的是 array,将会按照一定格式显示键和元素。object 与数组类似。

记住,print_r() 将把数组的指针移到最后边。使用 reset() 可让指针回到开始处。

 

如果想捕捉 print_r() 的输出,可使用 return 参数。若此参数设为 TRUE,print_r() 将不打印结果(此为默认动作),而是返回其输出。


<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x','y','z'));
print_r ($a);
?>

例子 return 参数示例

<?php
$b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z'));
$results = print_r ($b, true); //$results 包含了 print_r 的输出结果
?>


1. 合并数组
array array_merge (array array1 array2…,arrayN)

<?php

$fruits = array("apple","banana","pear");
$numbered = array("1","2","3");
$cards = array_merge($fruits, $numbered);
print_r($cards);

// output
// Array ( [0] => apple [1] => banana [2] => pear [3] => 1 [4] => 2 [5] => 3 )
?>

2. 追加数组
array array_merge_recursive(array array1,array array2[…,array arrayN])

array_merge_recursive()函数与array_merge()相同,可以将两个或多个数组合并在一起,形成一个联合的数组.两者之间的区别在于,当某个输入数组中的某个键己经存在于结果数组中时该函数会采取不同的处理方式.array_merge()会覆盖前面存在的键/值对,替换为当前输入数组中的键/值对,而array_merge_recursive()将把两个值合并在一起,形成一个新的数组,并以原有的键作为数组名。还有一个数组合并的形式,就是递归追加数组。

<?php

$fruit1 = array("apple" => "red", "banana" => "yellow");
$fruit2 = array("pear" => "yellow", "apple" => "green");
$result = array_merge_recursive($fruit1, $fruit2);
print_r($result);

// output
// Array ( [apple] => Array ( [0] => red [1] => green ) [banana] => yellow [pear] => yellow )
?>

3. 连接数组
array array_combine(array keys,array values)

array_combine()函数会得到一个新数组,它由一组提交的键和对应的值组成
<?php
$name = array("apple", "banana", "orange");
$color = array("red", "yellow", "orange");
$fruit = array_combine($name, $color);
print_r($fruit);

// output
// Array ( [apple] => red [banana] => yellow [orange] => orange )
?>

php 操作数组 (合并,拆分,追加,查找,删除等)

http://justcoding.iteye.com/blog/1181962/

 

php手册

http://www.kuqin.com/php5_doc/function.print-r.html

posted @ 2014-03-15 15:11  WR-HAPPY  阅读(82)  评论(0)    收藏  举报