x2p x2p - 1 month ago 6
PHP Question

Building a multidimensional Array with another Array in PHP

I try to build an array. I don't wanna write something like $array[3][5][8] = []. Because the count of the first Array can change, here it's 3 but it also can be like 9 or 12. Also the values can change, but they are always unique numbers. I hope someone knows a better way. Thank you.

// First Array, which I have. The count and the content can change.
array(3) {
[0]=>
string(1) "3"
[1]=>
string(1) "5"
[2]=>
string(1) "8"
}

// Second Array, thats the goal.
array(1) {
[3]=>
array(1) {
[5]=>
array(1) {
[8]=>
array(0) {
}
}
}
}

Answer

This code will solve your problem:

$array = [3,5,8,9]; // your first array 

$newArray = null;
foreach ($array as $value) {
    if($newArray === null) {
        $newArray[$value] = [];
        $ref = &$newArray[$value];
    }
    else {
        $ref[$value] = [];
        $ref = &$ref[$value];
    }
}

$newArray - holds the result you wanted