2014-08-28 74 views
1

我有一個充滿數據庫記錄的數組。它可能有很多元素或很少,它會定期變化。PHP:如何將數組拆分爲2個部分?

我需要將數組拆分成兩個相等的部分。原因是我然後將這些數組傳遞給Laravel視圖並將它們顯示在單獨的列中。

這裏是被拉到DB記錄:

$books = Book::where('unitcode', '=', $unitcode['unitcode'])->get();

如果拉式的作品,然後我運行此:

return View::make('showbooks') 
->with('books', $books); 

我想要做的就是通過$books1$books2這實際上是$books分成2部分。

關於如何做到這一點的任何想法?謝謝

+0

'array_chunk()' – 2014-08-28 03:43:48

+0

@scrowler請你能發表一個關於它的用途的答案嗎?我對此很新,並且無法找到數組的長度然後將其大塊。 – KriiV 2014-08-28 03:45:12

+0

'$ books = array_chunk($ books,count($ books)/ 2);' - 將它分成兩半 – 2014-08-28 03:46:03

回答

12

這是一個襯裏:

$halved = array_chunk($books, ceil(count($books)/2)); 

然後$halved[0]將包含陣列的第一半。在數組包含奇數個元素的情況下,它將總是大1個元素。當然,$halved[1]將包含數組的後半部分。

Here's a working example

+0

+1爲最簡單的一行方法:) – 2014-08-28 04:04:18

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); 
?> 
+1

如果'$ books'具有奇數個元素,則一個元素將被忽略......我將刪除'$ books2'的第二個'$ half'參數,這樣您可以從其中取出數組的其餘部分'$ books1'結束了...... – 2014-08-28 03:56:16

0

我想你應該使用的計數方法,然後循環的項目,直到中間它應該是這樣走的數組的長度:

<?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]; 
     } 
    } 
?>