[英]PHP: How to split array into 2 parts?
我有一个充满数据库记录的数组。 它可能有很多元素,也可能很少,它会定期变化。
我需要将数组分成两个相等的部分。 原因是我将这些 arrays 传递给 Laravel 视图并将它们显示到单独的列中。
这是正在提取的数据库记录:
$books = Book::where('unitcode', '=', $unitcode['unitcode'])->get();
如果拉动有效,那么我正在运行:
return View::make('showbooks')
->with('books', $books);
我想要做的是通过$books1
和$books2
这实际上是$books
分成两部分。
关于我如何做到这一点的任何想法? 谢谢
这是一个班轮:
$halved = array_chunk($books, ceil(count($books)/2));
然后$halved[0]
将包含数组的前半部分。 如果数组包含奇数个元素,它将总是大 1 个元素。 当然, $halved[1]
将包含数组的第二半。
我认为这对你有用。
<?php
$books = array("a", "b", "c", "d", "e","f"); // assuming books is an array like this
$count = count($books); // total count of the array books
$half = $count/2; // half of the total count
$books1 = array_slice($books, 0, $half); // returns first half
$books2 = array_slice($books, $half); // returns second half
print_r($books1);
print_r($books2);
?>
我认为您应该使用 count 方法获取数组的长度,然后将项目循环到中间,它应该如下所示:
<?php
$count = count($books); //getting the count of $books
$mid = round($count/2); //getting the mid point of $books
for($i = 0; $i < $count ; $i++){ //looping through the indexes
if($i <= mid - 1){ //Checking the position of $i and adding the value
$books1[] = $books[$i];
}else{
$books2[] = $books[$i];
}
}
?>
splitIn 方法将集合分成给定数量的组,在将剩余部分分配给最终组之前完全填充非终端组:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$groups = $collection->splitIn(3);
$groups->all();
// [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.