简体   繁体   中英

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.

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
                )

        )

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM