PHP – array_merge, array_chunk 用法

array_merge, array_chunk 用法

PHP basic function,array_merge, array_chunk,將兩個陣列合併或者將陣列分割,也用簡單的舉例來介紹吧!

  • array_merge
  • array_chunk 

array_merge

array_merge – 合併一個或多個陣列
array_merge ( array $array1 [, array $… ] )

$array1 = ['color' => 'red', 2, 4];
$array2 = ['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
)

$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);

Array
(
  [0] => data
)


array_chunk

array_chunk – 將陣列分割開來
array array_chunk ( array $array , int $size [, bool $preserve_keys = FALSE ] )
preserve_keys 為 true 會保留鍵名

$array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($array, 2));
print_r(array_chunk($array, 2, true));

Array(
  [0] => Array([0] => a [1] => b)
  [1] => Array([0] => c [1] => d)
  [2] => Array([0] => e)
)
Array(
  [0] => Array([0] => a [1] => b)
  [1] => Array([2] => c [3] => d)
  [2] => Array([4] => e)
)

一起討論吧