【PHP】数组处理
记录一下使用PHP数组执行合并和添加操作的方法以及结果。
合并数组
-
- キーが重複した場合、後の配列の値を返す。
- キーが数字の場合、振り直す。
$array1 = array('food' => 'yakiniku', 'red', 'blue');
$array2 = array(5 => 'black', 4 => 'white');
$array3 = array('food' => 'sushi', 'yellow');
$result = array_merge($array1, $array2, $array3);
print_r($array1);
print_r($array2);
print_r($array3);
print_r($result);
Array
(
[food] => yakiniku
[0] => red
[1] => blue
)
Array
(
[5] => black
[4] => white
)
Array
(
[food] => sushi
[0] => yellow
)
Array
(
[food] => sushi
[0] => red
[1] => blue
[2] => black
[3] => white
[4] => yellow
)
数组 + 数组
-
- キーが重複した場合、前の配列の値を返す。
- キーが数字の場合でも前の値を返す。
$array1 = array('food' => 'yakiniku', 'red', 'blue');
$array2 = array(5 => 'black', 4 => 'white');
$array3 = array('food' => 'sushi', 'yellow');
$result = $array1 + $array2 + $array3;
print_r($array1);
print_r($array2);
print_r($array3);
print_r($result);
Array
(
[food] => yakiniku
[0] => red
[1] => blue
)
Array
(
[5] => black
[4] => white
)
Array
(
[food] => sushi
[0] => yellow
)
Array
(
[food] => yakiniku
[0] => red
[1] => blue
[5] => black
[4] => white
)
合并递归数组
-
- キーが重複した場合、キーの値がひとつにまとめられる。
- キーが数字の場合、振り直す。
$array1 = array('food' => 'yakiniku', 'red', 'blue');
$array2 = array(5 => 'black', 4 => 'white');
$array3 = array('food' => 'sushi', 'yellow');
$result = array_merge_recursive($array1, $array2, $array3);
print_r($array1);
print_r($array2);
print_r($array3);
print_r($result);
Array
(
[food] => yakiniku
[0] => red
[1] => blue
)
Array
(
[5] => black
[4] => white
)
Array
(
[food] => sushi
[0] => yellow
)
Array
(
[food] => Array
(
[0] => yakiniku
[1] => sushi
)
[0] => red
[1] => blue
[2] => black
[3] => white
[4] => yellow
)
数组添加
-
- 一つ以上の要素を配列の最後に配列として追加する。
$array1[] = $array2; と同じ。array_pushの方が遅いらしい。
$array1 = array('food' => 'yakiniku', 'red', 'blue');
$array2 = array(5 => 'black', 4 => 'white');
$array3 = array('food' => 'sushi', 'yellow');
print_r($array1);
print_r($array2);
print_r($array3);
array_push($array1, $array2, $array3);
print_r($array1);
Array
(
[food] => yakiniku
[0] => red
[1] => blue
)
Array
(
[5] => black
[4] => white
)
Array
(
[food] => sushi
[0] => yellow
)
Array
(
[food] => yakiniku
[0] => red
[1] => blue
[2] => Array
(
[5] => black
[4] => white
)
[3] => Array
(
[food] => sushi
[0] => yellow
)
)
Hash::merge(CakePHP)可以进行数组合并。
-
- キーが重複した場合、後の配列の値を返す。
- キーが数字の場合、振り直さない。
$array1 = array('food' => 'yakiniku', 'red', 'blue');
$array2 = array(5 => 'black', 4 => 'white');
$array3 = array('food' => 'sushi', 'yellow');
$result = Hash::merge($array1, $array2);
print_r($array1);
print_r($array2);
print_r($array3);
print_r($result);
Array
(
[food] => yakiniku
[0] => red
[1] => blue
)
Array
(
[5] => black
[4] => white
)
Array
(
[food] => sushi
[0] => yellow
)
Array
(
[food] => sushi
[0] => red
[1] => blue
[5] => black
[4] => white
[2] => yellow
)