how to split the array in to two equal parts using php

梦想的初衷 提交于 2019-12-06 23:00:29

问题


how to split an array in to two equal parts using array_slice() in PHP ?

This is my requirement:

First array contains: 0-1200

Second array contains: 1200-end


回答1:


From the documentation for array_slice, all you have to do is give array_slice an offset and a length.

In your case:

$firsthalf = array_slice($original, 0, 1200);
$secondhalf = array_slice($original, 1200);

In other words, this code is telling 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.




回答2:


$quantity = count($original_collection);

$collection1 = array_slice($original_collection, 0, intval($quantity / 2), true);
$collection2 = array_diff_key($original_collection, $collection1);



回答3:


$array1 = array_slice($array, 0, 1199);
$array2 = array_slice($array, 1200);



回答4:


I think array_chunk would be easier, especially as you don't need to know how many elements are in the array.

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:


$array1 = array_slice($input, 0, 1200);
$array2 = array_slice($input, 1200);


来源:https://stackoverflow.com/questions/5561952/how-to-split-the-array-in-to-two-equal-parts-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!