本文实例讲述了PHP数组array类常见操作。分享给大家供大家参考,具体如下:
array_merge($arr1,$arr2....);//合并一个或多个数组
例:
1、
1
2
3
4
5
6
|
<?php
$beginning = 'foo' ;
$end = array (1 => 'bar' );
$result = array_merge (( array ) $beginning , ( array ) $end );
print_r( $result );
?>
|
以上例程会输出:
Array
(
[0] => foo
[1] => bar
)
2、
1
2
3
4
5
6
|
<?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、
1
2
3
4
5
|
<?php
$array1 = array ();
$array2 = array (1 => "data" );
$result = array_merge ( $array1 , $array2 );
?>
|
别忘了数字键名将会被重新编号!
Array
(
[0] => data
)
4、
1
2
3
4
5
6
|
<?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 及任何其它参数数组中的值。)
例:
1
2
3
4
5
6
|
<?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 中但是不在任何其它参数数组中的值
1
2
3
4
5
6
|
<?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 数组中的数字或者字符串的键名。)
1
2
3
4
5
6
7
8
9
10
11
|
<?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:单元长度
1
2
3
4
|
$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"
|
希望本文所述对大家PHP程序设计有所帮助。
原文链接:https://blog.csdn.net/qq_42176520/article/details/82791788