本节内容:
10个php数组操作实例代码,掌握下php数组合并与拆分的方法。
1、array_intersect array_intersect_assoc
复制代码 代码示例:
<?php
// array_intersect 求数组“值”的交集,索引为第一个数组的索引$arr = array(‘a’, ‘b’, ‘c’, ‘d’);
$arr2 = array(‘c’, ‘d’, ‘e’, ‘f’);$tmp = array_intersect($arr, $arr2);print_r($tmp); //Array ( [2] => c [3] => d )
echo “<hr/>”;/*
array_intersect_assoc 求交集的话,不仅要“值”相等,还要求键相等
*/$arr = array(‘a’, ‘b’, ‘c’, ‘d’);
$arr2 = array(‘c’, ‘d’, ‘e’, ‘f’);
$tmp = array_intersect_assoc($arr, $arr2);print_r($tmp); //Array ( )
echo “<hr/>”;$arr = array(‘a’, ‘b’, 100=>’c', ‘d’);
$arr2 = array(100=>’c', ‘d’, ‘e’, ‘f’);$tmp = array_intersect_assoc($arr, $arr2);print_r($tmp); //Array ( [100] => c [101] => d )
echo “<hr/>”;
?>
2、arra_diff array_diff_assoc
复制代码 代码示例:
<?php
/*求数组的差集
arra_diff是输出第一个数组里面有的元素”值”而后面的数组”们”没有的元素”值”
*/ www.jb200.com
$arr = array(‘a’, ‘b’, ‘c’, ‘d’);
$arr2 = array(‘c’, ‘d’, ‘e’, ‘f’);$tmp = array_diff($arr, $arr2);print_r($tmp); //Array ( [0] => a [1] => b )
echo “<hr/>”;################################################################################
/*
array_diff_assoc 是输出第一个数组里面有的”键值对”而后面的数组”们”没有的”键值对”
*/
$arr = array(‘a’, ‘b’, ‘c’, ‘d’);
$arr2 = array(‘c’, ‘d’, ‘e’, ‘f’);$tmp = array_diff_assoc($arr, $arr2);print_r($tmp); //Array ( [0] => a [1] => b [2] => c [3] => d )echo “<hr/>”;?>
3、array_merge
复制代码 代码示例:
<?php
/*
array_merge函数不会改变数组的排序,只是按照数组的前后顺序依次合并
*/$arr1 = array(“zhejiang” => “浙江”, “jiangsu” => “江苏”, “anhui” => “安徽”);
$arr2 = array(“shagnhai” => “上海”, “nanjing” => “南京”, “hefei” => “合肥”);
$arr3 = array(“xianggang” => “香港”, “taiwan” => “台湾”);$arrNew1 = array_merge($arr1, $arr2);
print_r($arrNew1);echo “<hr/>”;$arrNew2 = array_merge($arr1, $arr2, $arr3);
print_r($arrNew2);echo “<hr/>”;$arr4 = array(“xianggang” => “香港”, “taiwan” => “台湾”);
$arr5 = array(“aomen” => “澳门”, “taiwan” => “太湾”);
$arrNew3 = array_merge($arr4, $arr5);
print_r($arrNew3);?>
4、array_merge_recursive
复制代码 代码示例:
<?php$arr4 = array(“xianggang” => “香港”, “taiwan” => “台湾”);
$arr5 = array(“aomen” => “澳门”, “taiwan” => “太湾”);$tmp = array_merge_recursive($arr4, $arr5);print_r($tmp);/*
Array
(
[xianggang] => 香港
[taiwan] => Array
(
[0] => 台湾
[1] => 太湾
)[aomen] => 澳门
)
*//*如果是array_merge
Array
(
[xianggang] => 香港
[taiwan] => 太湾
[aomen] => 澳门
)
*/?>
5、range
复制代码 代码示例:
<?php
$arr = range(100, 110);$tmp = array_rand($arr);
print_r($tmp); //返回一个随机索引“数字”
echo “<hr/>”;
$tmp = array_rand($arr, 3);
print_r($tmp); //返回一个随机索引”数组”
echo “<hr/>”;$arr = array(
‘a’ => 1
, ‘b’ => 2
, ‘c’ => 3
);$tmp = array_rand($arr);
print_r($tmp); //返回一个随机”数字”
echo “<hr/>”;
$tmp = array_rand($arr, count($arr));
print_r($tmp); //返回一个随机索引”数组”
echo “<hr/>”;?>