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

is there a PHP function that would create a (deep) array key from an array ? It's quite difficult to explain, see that example:

function mysterious_function($input,$keys,$value){
    //...
    return $output;
}

$array = array(
    'hello'=>array(
        'im'=>'okay'
    )
);

$array = mysterious_function($array,array('hello','youre'),'beautiful');
$array = mysterious_function($array,array('ilove','the'),'haircut');

//would output

array(
    'hello'=>array(
        'im' =>         'ok',
        'youre' =>      'beautiful',
    ),
    'ilove'=>array(
        'the' =>        'haircut'
    )
);


Solution 1:[1]

I don't know if this could help you:

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

Yes, it's brutal :-D

Demo: http://sandbox.onlinephpfunctions.com/code/3091e831982df4f4fafca6f7e1fd05c31cdee526

Edit:

Often eval() is evil. Often there is another way to do this; by the way I hope this could help you.

Solution 2:[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"
            }
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 mcstafford