Php array from set of keys

前端 未结 1 1291
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-29 11:00

Found this post that helped me out: Split a string to form multidimensional array keys?

Anyhow that works like a charm when it comes to string values, but if array keys

相关标签:
1条回答
  • 2021-01-29 11:54

    Solution

    Here's the function that does the magic:

    function constructArray( &$array_ptr, $keys, $value )
        {
            // extract the last key
            $last_key = array_pop ( $keys );
    
            foreach ( $keys as $arr_key )
            {
                 unset($keys[$arr_key]);
                 if ( !array_key_exists ( strval($arr_key), $array_ptr ) )
                {
                    $array_ptr[ strval($arr_key) ] = array ( );
                }
                $array_ptr = &$array_ptr[ strval($arr_key) ];
            }
    
            // set the final key
            $array_ptr[ $last_key ] = $value;
        }
    

    Usage:

    $keys = array('variable_data', '0', 'var_desc');
    $clean_arr = array();
    constructArray($clean_arr, $keys, 'asd');
    
    // Output
    Array
    (
        [variable_data] => Array
            (
                [0] => Array
                    (
                        [var_desc] => asd
                    )
    
            )
    
    )
    
    0 讨论(0)
提交回复
热议问题