PHP: set a (deep) array key from an array [closed]



PHP Snippet 1:

function mysterious_function($array,$keys,$value){
    
    $stack = "";
    foreach($keys as $k){
        $stack .= "['{$k}']";
    }
    eval("\$array{$stack} = \$value;");
    
    return $array;
    
}

PHP Snippet 2:

<?
// I think I understand your use-case: Say I receive data expressed in a format like "Earth Science : Geology : Late Permian : Ice Depth = 30 feet"
// Parsing off the fact at the right is easy; setting the facts into a hierarchy is harder

function appendDeepArrayItem(&$array, $keys, $value)
{
    if (!is_array($array)) {
        die("First argument must be an array");
    }
    if (!is_array($keys)) {
        die("Second argument must be an array");
    }

    $currentKey = array_shift($keys);

    // If we've worked our way to the last key...
    if (count($keys) == 0) {
        if (is_array($value)) {
            foreach($value as $k=>$v) {
                $array[$currentKey][$k] = $v;
            }
        } else {
            $array[$currentKey][] = $value;
        }

    // Recurses Foiled Again! gotta keep digging... 
    } else {
        if (!array_key_exists($currentKey, $array)) {
            $array[$currentKey] = [];
        }
        appendDeepArrayItem($array[$currentKey], $keys, $value);
    }
}


$tree = [];

$parentKeys = explode(':', preg_replace('/\W:\W/', ':', "Earth Science : Geology : Late Permian"));
appendDeepArrayItem($tree, $parentKeys, ['Ice-depth in my back yard'=>'20 feet']);
appendDeepArrayItem($tree, $parentKeys, ['Unladen sparrow speed'=>'97 feet/second']);

$parentKeys = explode(':', preg_replace('/\W:\W/', ':', "Earth Science : Geology : Late Permian : About Frogs"));
appendDeepArrayItem($tree, $parentKeys, ['Croak loudness'=>'Very very loud']);

$parentKeys = explode(':', preg_replace('/\W:\W/', ':', "Earth Science : Geology : Paleoarchean"));
appendDeepArrayItem($tree, $parentKeys, ['Ice-depth in my back yard'=>'300 feet']);

echo "<pre>" . json_encode($tree, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

// Produces the following output:    
{
    "Earth Science": {
        "Geology": {
            "Late Permian": {
                "Ice-depth in my back yard": "20 feet",
                "Unladen sparrow speed": "97 feet/second",
                "About Frogs": {
                    "Croak loudness": "Very very loud"
                }
            },
            "Paleoarchean": {
                "Ice-depth in my back yard": "300 feet"
            }
        }
    }
}