PHP数组array类常见操作示例
本文实例讲述了php数组array类常见操作。分享给大家供大家参考,具体如下:
array_merge($arr1,$arr2....);//合并一个或多个数组
例:
1、
<?php $beginning = 'foo'; $end = array(1 => 'bar'); $result = array_merge((array)$beginning, (array)$end); print_r($result); ?>
以上例程会输出:
array
(
[0] => foo
[1] => bar
)
2、
<?php $array1 = array("color" => "red", 2, 4); $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4); $result = array_merge($array1, $array2); print_r($result); ?>
以上例程会输出:
array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)
3、
<?php $array1 = array(); $array2 = array(1 => "data"); $result = array_merge($array1, $array2); ?>
别忘了数字键名将会被重新编号!
array
(
[0] => data
)
4、
<?php $array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a'); $array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b'); $result = $array1 + $array2; var_dump($result); ?>
运行结果:
array(5) {
[0]=>
string(6) "zero_a"
[2]=>
string(5) "two_a"
[3]=>
string(7) "three_a"
[1]=>
string(5) "one_b"
[4]=>
string(6) "four_b"
}
array_diff($arr1,$arr2);//计算数组的差集(对比返回在 array1 中但是不在 array2 及任何其它参数数组中的值。)
例:
<?php $array1 = array("a" => "green", "red", "blue", "red"); $array2 = array("b" => "green", "yellow", "red"); $result = array_diff($array1, $array2); print_r($result); ?>
在 $array1 中多次出现的值一样处理,输出结果为:
array
(
[1] => blue
)
array_diff_assoc($arr1,$arr2...);//带索引检查计算数组的差集
array_diff_assoc() 返回一个数组,该数组包括了所有在 array1 中但是不在任何其它参数数组中的值
<?php $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red"); $array2 = array("a" => "green", "yellow", "red"); $result = array_diff_assoc($array1, $array2); print_r($result); ?>
以上例程会输出:
array
(
[b] => brown
[c] => blue
[0] => red
)
array_keys($array);//返回数组中部分的或所有的键名(返回 input 数组中的数字或者字符串的键名。)
<?php $array = array(0 => 100, "color" => "red"); print_r(array_keys($array)); $array = array("blue", "red", "green", "blue", "blue"); print_r(array_keys($array, "blue")); $array = array("color" => array("blue", "red", "green"), "size" => array("small", "medium", "large")); print_r(array_keys($array)); ?>
以上例程会输出:
array
(
[0] => 0
[1] => color
)
array
(
[0] => 0
[1] => 3
[2] => 4
)
array
(
[0] => color
[1] => size
)
array_slice($array, $offset, $length);//从数组中取出一段
参数:array::输入的数组, offset:序列偏移量, length:单元长度
$input = array("a", "b", "c", "d", "e"); $output = array_slice($input, 2); // returns "c", "d", and "e" $output = array_slice($input, -2, 1); // returns "d" $output = array_slice($input, 0, 3); // returns "a", "b", and "c"
上一篇: 解决ASP.NET中的各种乱码问题总结
下一篇: 南宋最骄傲的一场海战,揭秘胶西海战的结果