how to split an array in to two equal parts using array_slice() in PHP ?
如何在PHP中使用array_slice()将数组分成两个相等的部分?
This is my requirement:
First array contains: 0-1200
第一个数组包含:0 - 1200
Second array contains: 1200-end
第二个数组包含:1200 -结束
5 个解决方案
#1
13
From the documentation for array_slice, all you have to do is give array_slice
an offset and a length.
从array_slice的文档中,您所要做的就是给array_slice一个偏移量和长度。
In your case:
在你的例子:
$firsthalf = array_slice($original, 0, 1200);
$secondhalf = array_slice($original, 1200);
In other words, this code is telling array_slice
:
换句话说,这个代码告诉array_slice:
take the first 1200 records;
then, take all the records starting at index 1200;
Since index 1200 is item 1201, this should be what you need.
由于索引1200是项目1201,这应该是你需要的。
#2
11
$quantity = count($original_collection);
$collection1 = array_slice($original_collection, 0, intval($quantity / 2), true);
$collection2 = array_diff_key($original_collection, $collection1);
#3
7
$array1 = array_slice($array, 0, 1199);
$array2 = array_slice($array, 1200);
#4
6
I think array_chunk
would be easier, especially as you don't need to know how many elements are in the array.
我认为array_chunk会更简单,尤其是您不需要知道数组中有多少元素。
array array_chunk ( array $input , int $size [, bool $preserve_keys = false ] )
<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
$size = ceil(count($input_array)/2));
print_r(array_chunk($input_array, $size));
print_r(array_chunk($input_array, $size, true));
?>
#5
5
$array1 = array_slice($input, 0, 1200);
$array2 = array_slice($input, 1200);
#1
13
From the documentation for array_slice, all you have to do is give array_slice
an offset and a length.
从array_slice的文档中,您所要做的就是给array_slice一个偏移量和长度。
In your case:
在你的例子:
$firsthalf = array_slice($original, 0, 1200);
$secondhalf = array_slice($original, 1200);
In other words, this code is telling array_slice
:
换句话说,这个代码告诉array_slice:
take the first 1200 records;
then, take all the records starting at index 1200;
Since index 1200 is item 1201, this should be what you need.
由于索引1200是项目1201,这应该是你需要的。
#2
11
$quantity = count($original_collection);
$collection1 = array_slice($original_collection, 0, intval($quantity / 2), true);
$collection2 = array_diff_key($original_collection, $collection1);
#3
7
$array1 = array_slice($array, 0, 1199);
$array2 = array_slice($array, 1200);
#4
6
I think array_chunk
would be easier, especially as you don't need to know how many elements are in the array.
我认为array_chunk会更简单,尤其是您不需要知道数组中有多少元素。
array array_chunk ( array $input , int $size [, bool $preserve_keys = false ] )
<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
$size = ceil(count($input_array)/2));
print_r(array_chunk($input_array, $size));
print_r(array_chunk($input_array, $size, true));
?>
#5
5
$array1 = array_slice($input, 0, 1200);
$array2 = array_slice($input, 1200);