Using a path to an array item

前端 未结 1 1903
你的背包
你的背包 2021-01-25 05:41

Is there a way to reference an item within a multidimensional array by using a path or an array of path elements? EG.

$multi = array
(
    \'array_1\' => arra         


        
相关标签:
1条回答
  • 2021-01-25 06:01

    There's nothing built into PHP to do this but you can write a function for it, using a moving reference:

    /**
     * @param string $path path in the form 'item_1.item_2.[...].item_n'
     * @param array $array original array
     */
    function &get_from_array($path, &$array)
    {
        $current =& $array;
        foreach(explode('.', $path) as $key) {
            $current =& $current[$key];
        }
        return $current;
    }
    

    Example:

    // get element:
    $result = get_from_array('level_1.level_2.option_1', $multi);
    echo $result; // --> value_1
    
    $result = 'changed option';
    echo $multi['level_1']['level_2']['option_1']; // --> changed_option
    

    I wrote it to convert names from configuration files to arrays, if you want to pass the path itself as an array like in your example, just leave out the explode.

    0 讨论(0)
提交回复
热议问题