Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array to Multidimensional Array

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
  )
)
like image 514
Tim Avatar asked Feb 06 '11 23:02

Tim


People also ask

How do you make a multidimensional array?

You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.

How do you reshape an array to a 2d array?

convert a 1-dimensional array into a 2-dimensional array by adding new axis. a=np. array([10,20,30,40,50,60]) b=a[:,np. newaxis]--it will convert it to two dimension.

How do I convert multiple arrays into one array?

Use numpy. concatenate() to merge the content of two or multiple arrays into a single array. This function takes several arguments along with the NumPy arrays to concatenate and returns a Numpy array ndarray. Note that this method also takes axis as another argument, when not specified it defaults to 0.

Is multidimensional array PHP?

A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.


1 Answers

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.

like image 195
BoltClock Avatar answered Oct 02 '22 16:10

BoltClock