-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 ?

2
  • 5
    Post the solution as an answer, and mark the answer as the correct answer. Do not put the solution in the question. Commented May 26, 2012 at 11:23
  • ahh always wondered how to do that, but there is time limit when answering own question :S Commented May 26, 2012 at 11:34

1 Answer 1

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
                )

        )

)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.