Jump to content

Dynamically building a multidimensional array


joel24

Recommended Posts

I'm trying to convert a one dimensional array into a multidimensional array by grouping matching parts of the keys,

i.e. array('onetwothreefour'=>'value',

                'onetwothreesix'=>'value2')

would become

array('onetwothree'=>array('four'=>'value',

                                             'six'=>'value2'));

 

Essentially I'm trying to convert XML to YML and have a one dimensional array of the XML with index => value.

 

I've been staring at it for a while now and have tried a few recursive functions to build it though I've come to a few dead ends and would appreciate any words of wisdom if someone can spot the answer easier than I

Have you looked into array_merge()? http://us3.php.net/manual/en/function.array-merge.php and there recursive array functions http://us3.php.net/manual/en/function.array-merge-recursive.php there as well that might do the trick for you. However, i have encountered problems myself if the array starts getting really huge when using recursive, but that could had just been me.

Now the question, how to create a multidimensional array from a 1d array?

 

i.e.

$key = 'one_two_three';
$multiKeys=explode('_',$key);

//now multikey = array('one','two','three');

//I'd like to convert this to
$newArray['one']['two']['three'];

I've tried a recursive function though I need to get to the end of the array and I think I've just been staring at this one for a little too long =/

Any help would be appreciated,

Do you mean

$a = array (
        'AA_BB_CC' => 1,
        'AA_BB_DD' => 2,
        'AA_BB_EE' => 3,
        'AA_CC_DD' => 4,
        'AA_CC_EE' => 5,
        'AA_DD_FF' => 6
    );

$b = array();
foreach ($a as $k => $v) {
    $keys = explode('_', $k);
    $b[$keys[0]][$keys[1]][$keys[2]] = $v;
}

echo '<pre>',print_r($b, true),'</pre>';

giving:

Array
(
    [AA] => Array
        (
            [BB] => Array
                (
                    [CC] => 1
                    [DD] => 2
                    [EE] => 3
                )

            [CC] => Array
                (
                    [DD] => 4
                    [EE] => 5
                )

            [DD] => Array
                (
                    [FF] => 6
                )

        )

)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.