Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP arrays - How to 1-dimensional array into nested multidimensional array?

When retrieving a hierarchical structure from MySQL (table with one ID column and one PARENT column signifying the hierarchical relationships), I map the result into an enumerated array as follows (for this example the numbers are arbitrary):

Array ( [3] => Array ( [7] => Array () ), [7] => Array ( [8] => Array () ) )

Notice 3 is the parent of 7, and 7 is the parent of 8 (this could go on and on; and any parent could have multiple children).

I wanted to shrink this array into a nested multidimensional array as follows:

Array ( [3] => Array ( [7] => Array ( [8] => Array () ) ) )

That is, each NEW id is automatically assigned an empty array. Regardless, any ID's children will be pushed into their parent's array.

Take a look at the following illustration for further clarification:

alt text http://img263.imageshack.us/img263/4986/array.gif

This will probably result in a complicated recursive operation, since I always have to check whether a parent with any certain ID already exists (and if so, push the value into its array).

Is there a built-in php function that can assist me with this? Do you have any idea as to how to go about constructing this? For what it's worth I'm using this to built a navigation bar in wordpress (which can contain categories, subcategories, posts... essentially anything).

like image 231
Gal Avatar asked May 23 '10 17:05

Gal


People also ask

How do you convert a one-dimensional array into two dimensions?

Use reshape() Function to Transform 1d Array to 2d Array The number of components within every dimension defines the form of the array. We may add or delete parameters or adjust the number of items within every dimension by using reshaping. To modify the layout of a NumPy ndarray, we will be using the reshape() method.

How can create multidimensional array in array in PHP?

You create a multidimensional array using the array() construct, much like creating a regular array. The difference is that each element in the array you create is itself an array. For example: $myArray = array( array( value1 , value2 , value3 ), array( value4 , value5 , value6 ), array( value7 , value8 , value9 ) );

Is multidimensional array and nested array same?

Perhaps, a multidimensional array is always regular and has an associated type constraint (and can therefore have storage layouts and access patterns optimised for that regularity), whereas a nested array can be jagged, and perhaps the inner levels of a nested array can be missing altogether.

How do you convert a one-dimensional array to a two dimensional array in C?

So the total number of elements of 1D array = (​ m * n ​ ) elements. Call the function​ ​ input_array​ to store elements in 1D array. Call the function ​ print_array​ to print the elements of 1D array. Call the function ​ array_to_matrix​ to convert 1D array to 2D array.


2 Answers

The idea is that you keep an auxiliary array with all the nodes (parent and child) you find. The values of this arrays are references that back your result.

This builds the tree in linear time (array_key_exists does a hash table lookup, which is on average O(1)):

//table contains (id, parent)
$orig = array(
    11 => 8,
    7 => 3,
    8 => 7,
    99 => 8,
    16 => 8,
);

$childrenTable = array();
$result = array();

foreach ($orig as $n => $p) {
    //parent was not seen before, put on root
    if (!array_key_exists($p, $childrenTable)) {
        $childrenTable[$p] = array();
        $result[$p] = &$childrenTable[$p];
    }
    //child was not seen before
    if (!array_key_exists($n, $childrenTable)) {
        $childrenTable[$n] = array();
    }

    //root node has a parent after all, relocate
    if (array_key_exists($n, $result)) {
        unset($result[$n]);
    }

    $childrenTable[$p][$n] = &$childrenTable[$n];
}
unset($childrenTable);

var_dump($result);

gives

array(1) {
  [3]=>
  array(1) {
    [7]=>
    array(1) {
      [8]=>
      array(3) {
        [11]=>
        array(0) {
        }
        [99]=>
        array(0) {
        }
        [16]=>
        array(0) {
        }
      }
    }
  }
}

EDIT: unset $childrenTable in the end to clear reference flags. In practice, you will probably want to do the operation inside a function anyway.

like image 53
Artefacto Avatar answered Oct 22 '22 21:10

Artefacto


This question and it's answers should be helpful to you: turn database result into array.

Be sure to read the PDF presentation by @Bill Karwin, specifically the topics regarding the Closure table.

like image 33
Alix Axel Avatar answered Oct 22 '22 21:10

Alix Axel