-1

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 contain integers then it misses these.

Here is the demo:

i got set of keys:

Array
(
    [0] => variable_data
    [1] => 0
    [2] => var_type
)

And method to create e nested array

function constructArray( &$array_ptr, $keys, $value )
    {
        // extract the last key
        $last_key = array_pop ( $keys );

        // walk/build the array to the specified key
        while ( $arr_key = strval( array_shift ( $keys ) ) )
        {
            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';
    }

And i use it in this way:

$keys = array(
    'variable_data',
    '0',
    'var_type'
);
    $clean_arr = array();
    constructArray($clean_arr, $keys, 'asd');

but the output looks like this:

Array
(
    [variable_data] => Array
        (
            [var_desc] => $value
        )

)

As you see, variable_data index is not containing 0 index. I have tested allmost everything that i might know to work but it didnt. Anyone who has better clue ?

Community
  • 1
  • 1
Deko
  • 1,028
  • 2
  • 15
  • 24
  • 5
    Post the solution as an answer, and mark the answer as the correct answer. Do not put the solution in the question. – Thom Wiggers May 26 '12 at 11:23
  • ahh always wondered how to do that, but there is time limit when answering own question :S – Deko May 26 '12 at 11:34

1 Answers1

0

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
                )

        )

)
Community
  • 1
  • 1
Deko
  • 1,028
  • 2
  • 15
  • 24