php 如何使用php将数组拆分/划分为2?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14115976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split/divide an array into 2 using php?
提问by Aravinthan
Help me to split or divide an array into 2 different arrays. Here is my single array
帮助我将数组拆分或划分为 2 个不同的数组。这是我的单个阵列
$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");
回答by Joseph Silber
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:
list($array1, $array2) = array_chunk($array, ceil(count($array) / 2));
回答by Brad Christie
array_sliceworks 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);

