SmootQ
SmootQ

Reputation: 2122

Group elements in collections of arrays

I have this code, it fetches data from CSV file using splFileObject:

while(!$this->_file->eof()){
     $data[$i] = $this->_file->fgetcsv();
}

This is the result :

array(12) {
  [0]=>
  array(1) {
    [0]=>
    string(41) "134550;651099595;3004050;1340.03;16/04/15"
  }
  [1]=>
  array(1) {
    [0]=>
    string(41) "134333;651099594;3004051;1500.03;10/08/15"
  }
 [2]=>
  array(1) {
    [0]=>
    string(41) "134550;651099595;3004050;1340.03;16/04/15"
  }
  [3]=>
  array(1) {
    [0]=>
    string(41) "134333;651099594;3004051;1500.03;10/08/15"
  }
}

What I want to do , is to group the arrays by collections of 2 (or whatever) like this (e.g of count = 2):

 array(12) {
    [0] => 
    array(2){
          [0]=>
       array(1) {
        [0]=>
        string(41) "134550;651099595;3004050;1340.03;16/04/15"
        }
           [1]=>
        array(1) {
        [0]=>
        string(41) "134550;651099595;3004050;1340.03;16/04/15"
        }
    }
    [1] =>
    array(2){
          [0]=>
       array(1) {
        [0]=>
        string(41) "134550;651099595;3004050;1340.03;16/04/15"
        }
           [1]=>
        array(1) {
        [0]=>
        string(41) "134550;651099595;3004050;1340.03;16/04/15"
        }
    }
}

Upvotes: 0

Views: 41

Answers (1)

Mark Baker
Mark Baker

Reputation: 212412

Sounds like a job for array_chunk()

$data = array_chunk($data, 2);

Upvotes: 1

Related Questions