Neigyl R. Noval
Neigyl R. Noval

Reputation: 6038

How to create a tree-like array from a loop?

Suppose I have a one-dimensional array $arr like this:

Array
(
    ['key1'] => 1
    ['key2'] => 1
    ['key3'] => 1
    ['key4'] => 1
)

I want to loop through $arr like this:

foreach($arr as $key => $a) {
   //$tree[????] = ????? Here is my concern
}

such that, doing print_r($tree) produces

Array
(
    ['key1'] => Array
    (
        ['key2'] => Array
        (
            ['key3'] => Array
            (
                ['key4'] => 1
            )
        )
    )
)

My concern is how to increase the dimension (not the values) of the array $tree inside the loop from a single dimension array $numbers such that $tree['key1']['key2']['key3'] is an array and $tree['key1']['key2']['key3']['key4'] is equal to 1.

Furthermore, if I have a single dimensional array $foo with 10 elements. I should produce another array $bar that expands to 10 dimensional array similar to the output above.

What should I do inside the foreach loop? Or instead of using loop, is there a way to produce an output like that of above from a one dimension array?


EDIT:

OK well you obviously need some kind of recursive function, but can you explain how you know that key2 should be a child of key1, key3 should be a child of key2 etc based on the data you show?

The next element of a 1D array is a child of the previous element. So if the 1D array is like this:

Array
(
    ['bar'] => 1 // I don't care of the values as of the moment
    ['foo'] => 1
    ['baz'] => 1
)

Element foo should be the child of bar, and element baz should be the child of foo for the tree array.

Ok so the actual values of everything except the last element are irrelevant?

Actually all values of the 1D array is irrelevant as of this moment. I am only concerned on constructing the tree array.

Upvotes: 1

Views: 1769

Answers (2)

DaveRandom
DaveRandom

Reputation: 88647

The way to do this is to use references.

function create_tree($arr) {
  $result = array();
  $ref = &$result;
  foreach ($arr as $key => $el) {
    $ref = array($key => $el);
    $ref =& $ref[$key];
  }
  return $result;
}

How it works:

$result = array(); // an array to hold the result

$ref = &$result; // start with a reference to the top level

foreach ($arr as $key => $el) { // iterate over the input array

  $ref = array($key => $el); // create this level in the array

  $ref =& $ref[$key]; // change the reference to be the new deepest level

}

return $result; // return the result

See it working

Upvotes: 3

PleaseStand
PleaseStand

Reputation: 32072

Assignment by reference appears to be useful for this.

$tree = array();
$node =& $tree;
foreach ($arr as $key => $a) {
    $node =& $node[$key];
    $node = array();
}
$node = end($arr);

Upvotes: 2

Related Questions