user2642693
user2642693

Reputation: 3

Dynamically build and add dimensions to multidimensional array

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.

Upvotes: 0

Views: 58

Answers (1)

Fabricator
Fabricator

Reputation: 12772

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
                )

        )

)

Upvotes: 1

Related Questions