1

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?

Mansuro
  • 4,558
  • 4
  • 36
  • 76
carlo
  • 700
  • 2
  • 9
  • 25
  • The user is asking how to build a multidimensional array based on the values of an existing array. With the given array [1, 5, 6], he would like to build an array that looks like this: $array[1][5][6] – Chris Sobolewski Oct 21 '11 at 19:21
  • Well, I am not sure how the final function would look like, but this would be easy having a recursive function. – OptimusCrime Oct 21 '11 at 19:25
  • This question does have a [mcve]. What is the exact desired output from the sample input? `$index["1"]["5"]["6"] = []` or `$index["1"]["5"] = "6"`? – mickmackusa May 14 '22 at 11:47

2 Answers2

7

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.

aurora
  • 9,607
  • 7
  • 36
  • 54
3
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];
}
ben
  • 1,946
  • 2
  • 18
  • 26
  • Thank you ben, this does the trick. Now, at last, how could I assign a value to the last key (instead of an empty array)? – carlo Oct 21 '11 at 19:30