Search code examples
phparraysmultidimensional-arraygroupingsub-array

Split a flat array into subarrays based on a delimiting element


I like to convert a single array into a multidimensional array. This is what I get have web scraping a page, except it is not the end result that I am looking for.

Change:

Rooms: Array (
  [0] => name 
  [1] => value 
  [2] => size
  [3] =>  
  [4] => name 
  [5] => value 
  [6] => size
  [7] =>      
  [8] => name 
  [9] => value 
  [10] => size
  [11] =>  
  [12] => name 
  [13] => value 
  [14] => size
  [15] =>  
)

Into:

Rooms: Array (
  Room: Array (
    [0] => name 
    [1] => value 
    [2] => size
  ),
  Room: Array (
    [0] => name 
    [1] => value 
    [2] => size
  ),
  Room: Array (
    [0] => name 
    [1] => value 
    [2] => size
  )
)

Solution

  • First use array_filter() to get rid of the   nodes:

    $array = array_filter($array, function($x) { return trim($x) != ' '; });
    
    // Or if your PHP is older than 5.3
    $array = array_filter($array, create_function('$x', 'return trim($x) != " ";'));
    

    Then use array_chunk() to split the array into chunks of 3:

    $array = array_chunk($array, 3);
    

    This of course assumes you will always and only get tuples containing name, value and size, in that order.