0

I'm looking for a way to transform this code that works and gives me the expected result with 3 elements:

<?php
$arb = array(array("a", "b", "c"));
$arb_array = array();

foreach($arb as $a){

if(!array_key_exists($a[0], $arb_array)){
$arb_array[$a[0]] = array();
}

if(!array_key_exists($a[1], $arb_array[$a[0]])){
$arb_array[$a[0]][$a[1]]= array();
}

if(!array_key_exists($a[2], $arb_array[$a[0]][$a[1]])){
$arb_array[$a[0]][$a[1]][$a[2]]= array();
}

}
?>

into a dynamic one that could work regardless of the amount of elements present in $a But i'm stuck when i have to make the depth a php array dynamic

Thank you in advance for any suggestions !

1

1 Answer 1

1

You can solve this with references:

$arb = array(array("a", "b", "c"));
$arb_array = array();

$arr = &$arb_array;
foreach($arb as $a) {
    foreach($a as $key) {
        if(!array_key_exists($key, $arr))
            $arr[$key] = array();
        $arr = &$arr[$key];
    }
}

print_r($arb_array);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.