Help me to split or divide an array into 2 different arrays. Here is my single array
帮我把一个数组分割成两个不同的数组。这是我的单个数组
$array = array("1","2","3","4","5","6");
I want the above array into two array like below
我想把上面的数组分成如下所示的两个数组
$array1 = array("1","2","3");
$array2 = array("4","5","6");
3 个解决方案
#1
57
Use array_chunk
:
使用array_chunk:
$pieces = array_chunk($array, ceil(count($array) / 2));
If you want them in separate variables (instead of a multi-dimensional array), use list
:
如果你想把它们放在单独的变量中(而不是多维数组),请使用列表:
list($array1, $array2) = array_chunk($array, ceil(count($array) / 2));
#2
18
array_slice
works well as long as you know how many elements you want in each array:
只要知道每个数组中需要多少元素,array_slice就能很好地工作:
$array1 = array_slice($array, 0, 3);
$array2 = array_slice($array, 3, 3);
#3
0
If you want to split an array in two sub-array with an index delimiter that is not array_size/2
, you can use the function array_slice
like that :
如果您想将一个数组分成两个子数组,其中一个索引分隔符不是array_size/2,那么可以使用函数array_slice:
$init_array = array("foo", "bar", "toto");
$index = 1;
$array_1 = array_slice($init_array, 0, $index);
$array_2 = array_slice($init_array, $index);
To print the result :
打印结果:
print_r($init_array);
print_r($array_1);
print_r($array_2);
The output :
输出:
Array([0] => foo [1] => bar [2] => toto)
Array([0] => foo)
Array([0] => bar [1] => toto)
#1
57
Use array_chunk
:
使用array_chunk:
$pieces = array_chunk($array, ceil(count($array) / 2));
If you want them in separate variables (instead of a multi-dimensional array), use list
:
如果你想把它们放在单独的变量中(而不是多维数组),请使用列表:
list($array1, $array2) = array_chunk($array, ceil(count($array) / 2));
#2
18
array_slice
works well as long as you know how many elements you want in each array:
只要知道每个数组中需要多少元素,array_slice就能很好地工作:
$array1 = array_slice($array, 0, 3);
$array2 = array_slice($array, 3, 3);
#3
0
If you want to split an array in two sub-array with an index delimiter that is not array_size/2
, you can use the function array_slice
like that :
如果您想将一个数组分成两个子数组,其中一个索引分隔符不是array_size/2,那么可以使用函数array_slice:
$init_array = array("foo", "bar", "toto");
$index = 1;
$array_1 = array_slice($init_array, 0, $index);
$array_2 = array_slice($init_array, $index);
To print the result :
打印结果:
print_r($init_array);
print_r($array_1);
print_r($array_2);
The output :
输出:
Array([0] => foo [1] => bar [2] => toto)
Array([0] => foo)
Array([0] => bar [1] => toto)