0

I'm trying to build a multidimensional array based on some string values I have on the database. Basically the values are as following:

1
1.1
2
2.1
2.1.1
2.1.1.1
2.1.1.2

And so on. What I'm trying to achieve is something similar to this:

$arr[1] = 1
$arr[1][1] = 1
$arr[2] = 2
$arr[2][1] = 1
$arr[2][1][1] = 1
$arr[2][1][1][1] = 1
$arr[2][1][1][2] = 2

Can you please help me! Thanks in advance.

3
  • 1
    What are the relations with the values? Commented Jun 12, 2014 at 8:19
  • 2
    The value of an array is either a scalar value or another array. It cannot be both. Therefore the first two statements you are asking to be true cannot simultaneously be true.. Commented Jun 12, 2014 at 8:19
  • You need to specify your question more and not just ask for code.... Commented Jun 12, 2014 at 8:21

1 Answer 1

1

This kind of task is easiest to do with recursion:

<?php
$s = '2.1.1';
$arr = insert(array(), explode('.', $s), 0);

print_r($arr);
function insert($arr, $items, $i)
{
    if ($i < count($items)) {
        $x = $items[$i];
        $arr[$x] = array();
        if ($i == count($items)-1) {
            $arr[$x] = $x;
        } else if ($i < count($items)) {
            $arr[$x] = insert($arr[$x], $items, $i+1);
        }
    }

    return $arr;
}

outputs:

Array
(
    [2] => Array
        (
            [1] => Array
                (
                    [1] => 1
                )

        )

)
Sign up to request clarification or add additional context in comments.

Comments

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.