2

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.

1
  • 2
    You said, "Tried dynamic variable naming and dynamically creating multidimensional arrays, but both dont seem to work." - show us your code... Commented Nov 20, 2012 at 23:09

2 Answers 2

4

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Valid idea, but it would require some sort of sorted map inside so we wouldn't have to search the proper value everytime. Well, and an array in php is a sorted hash map, so this would be kind of redundant.

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.