5

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
  )
)

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

So that you don't need to keep track of group indexes in the result array, push references into the result array and only push elements into the current reference. Because the delimiting element only occurs AFTER sets of data, avoid creating an empty last data set by only creating and pushing a new reference if a non-delimiter value is encountered. Demo

$result = [];
foreach ($array as $row) {
    if ($row === ' ') {
        unset($ref);
        continue;
    }
    if (!isset($ref)) {
        $result[] =& $ref;    
    }
    $ref[] = $row;
}
var_export($result);

Related content:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.