成都网站建设设计

将想法与焦点和您一起共享

数组array集合

一、比较两个数组之差:array_diff
例如:
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
$result=array_diff($a1,$a2);
print_r($result);
结果为:Array ( [d] => yellow )

成都创新互联公司 - 成都服务器托管,四川服务器租用,成都服务器租用,四川网通托管,绵阳服务器托管,德阳服务器托管,遂宁服务器托管,绵阳服务器托管,四川云主机,成都云主机,西南云主机,成都服务器托管,西南服务器托管,四川/成都大带宽,机柜大带宽、租用·托管,四川老牌IDC服务商

二、比较两个数组的交集:array_intersect
例如:
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
$result=array_intersect($a1,$a2);
print_r($result);
结果为:Array ( [a] => red [b] => green [c] => blue )

三、取出数组中的那些数据:array_slice
array_slice默认是不保留键名的。
使用array_slice函数要保留键名值,最后一个参数$preserve_keys设置为true即可。
例如:
$levels = array('a' => 1, 'b' =>2, 'c' => 3, 'd' => 4, 'f' => 5, 'g' => 6);
$firstLevels = array_slice($levels, 0, 5, true);
结果为:
$firstLevels = array('a' => 1, 'b' =>2, 'c' => 3, 'd' => 4, 'f' => 5);

四、合并数组:array_merge()
例如:
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
结果为:Array ( [0] => red [1] => green [2] => blue [3] => yellow )

五、取出二维数组中的某个字段:array_column()
例如:
$a = array(
array(
'id' => 5698,
'first_name' => 'Peter',
'last_name' => 'Griffin',
),
array(
'id' => 4767,
'first_name' => 'Ben',
'last_name' => 'Smith',
),
array(
'id' => 3809,
'first_name' => 'Joe',
'last_name' => 'Doe',
)

$last_names = array_column($a, 'last_name');
print_r($last_names);

结果为:
Array
(
[0] => Griffin
[1] => Smith
[2] => Doe
)

六、将数组一维数组分成二维数组: array_chunk()
例如:
$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
)
)


网页题目:数组array集合
网页路径:http://chengdu.cdxwcx.cn/article/jddscp.html