PHP one level deeper in each loop

I am trying to skip one array each time adding a new level to another array. Let me illustrate - $ arr variable values ​​are different every time

$arr = array("1","5","6");

Looping

$index[$arr[0]];

Looping

$index["1"][$arr[1]]  // "1" since this key was filled in by the previous loop, continuing with a new key

Looping

$index["1"]["5"][$arr[2]] // same as previous loop

- looped at all $ arr positions, the result is $ index ["1"] ["5"] ["6"] -

The problem is that I do not know how many values ​​the array contains $arr. Then I don’t know how to continue, for example, $index["1"]when the first value $arrwas looped to the next level of the array (in other words: add another key).

Is anyone

+1
source share
4 answers

:

$a = array("1","5","6");
$b = array();
$c =& $b;

foreach ($a as $k) {
    $c[$k] = array();
    $c     =& $c[$k];
}

Array 
    (
    [1] => Array
        (
            [5] => Array
                (
                    [6] => Array
                        (
                        )
                )
        )
)

, :

$c = 'blubber';

, $c , .

+6
function add_inner_array(&$array, $index) {
    if(isset($array[$index])) return true;
    else {
        $array[$index] = array();
        return true;
    }
}

$a = array(1,5,6);
$index = array();
$pass =& $index;
foreach($a as $k) {
    add_inner_array($pass, $k);
    $pass =& $pass[$k];
}
+3

, , ? , : , "" ? PHP?

0

, , , , : ,

0

All Articles