Simon Nouwens
Simon Nouwens

Reputation: 50

Hierarchical data into array

I need some logic for the following problem, but can't get my head around it. Basically I have some data like the following array

array(
    array('name' => 'Test1',
          'hierarchy'=> '1'),
    array('name' => 'Test2',
          'hierarchy'=> '1.1'),
    array('name' => 'Test3',
          'hierarchy'=> '1.2'),
    array('name' => 'Test4',
          'hierarchy'=> '1.2.1')
)

Now I would like to output an array in such a way that

$array[1] = 'Test1';
$array[1][2][1] = 'Test4';

Tried dynamic variable naming and dynamically creating multidimensional arrays, but both dont seem to work.

Upvotes: 2

Views: 136

Answers (2)

jaudette
jaudette

Reputation: 2313

If you don't absolutely need an array, you can create a class and extend ArrayClass or if you need only the array access, you can also implement ArrayAccess. From there, you can parse through your data and return the required values for your application.

Upvotes: 0

AndreKR
AndreKR

Reputation: 33678

That's not possible.

For $array[1] = 'Test1'; $array[1] needs to be a string, but for $array[1][2][1] = 'Test4'; it needs to be an array.

You could do something like this:

$array[1]['text'] = 'Test1';
$array[1][2][1]['text'] = 'Test4';

Here's code for that:

$result = array();

foreach ($input as $entry)
{
    $path_components = explode('.', $entry['hierarchy']);

    $pointer =& $result;
    foreach ($path_components as $path_component)
        $pointer =& $pointer[$path_component];

    $pointer['text'] = $entry['name'];

    unset($pointer);
}

Upvotes: 4

Related Questions