PHP One level deeper in array each loop made

2020-03-30 09:51发布

问题:

I'm trying to loop through one array, adding a new level to another array each time. Let me illustrate - variable $arr's values are different each 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 over all $arr's items, done, result is $index["1"]["5"]["6"]--

The problem is I won't know how much values the $arr array contains. Then, I don't know how to continue from, for example, $index["1"] when the first value of $arr has been looped to the next array level (other words: add another key)..

Anyone?

回答1:

You can use references here:

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

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

outputs

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

To overwrite the last element with some other value, you can just add the line:

$c = 'blubber';

after the loop, because $c is a reference to the deepest array level, when the loop is finished.



回答2:

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:

You basically want to see how deep an multi-dimensional array is, right? If so this should be helpful: Is there a way to find out how "deep" a PHP array is?



回答4:

I may be wrong, but I think you are asking the same as this question: Multidimensional Arrays Nested to Unlimited Depth