Dynamic array keys

前端 未结 5 1389
误落风尘
误落风尘 2020-11-29 06:45

I have a string like this:

$string = \'one/two/three/four\';

which I turn it into a array:

$keys = explode(\'/\', $string);

5条回答
  •  [愿得一人]
    2020-11-29 07:28

    $string = 'one/two/three/four';
    $keys = explode('/', $string);
    $arr = array(); // some big array with lots of dimensions
    $ref = &$arr;
    
    while ($key = array_shift($keys)) {
        $ref = &$ref[$key];
    }
    
    $ref = 'value';
    

    What this is doing:

    • Using a variable, $ref, to keep track of a reference to the current dimension of $arr.
    • Looping through $keys one at a time, referencing the $key element of the current reference.
    • Setting the value to the final reference.

提交回复
热议问题