TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Advanced PHP Programming (http://www.talkphp.com/advanced-php-programming/)
-   -   Build multi-dimensional array out of a flat array (http://www.talkphp.com/advanced-php-programming/2855-build-multi-dimensional-array-out-flat-array.html)

drewbee 05-28-2008 01:01 AM

Build multi-dimensional array out of a flat array
 
Hi All,

I am having some issues doing this. I think the only way to accomplish this is to use a recursive function, however I am failing miserably.

Basically, I need to turn a flat array into a multi-dimensional array.

The flat arrays *values* need to become the new *keys* to the multi-dimensional array.

The array I feed to it can have 1 value in it, up to nth high.
Example:
PHP Code:

// Starts out as
$array = array(=> '0',
                       
=> '15',
                       
=> '32',
                       
=> '18');

// Is turned into
$array = array('0' => 
                                array(
'15' =>
                                                    array(
'32' =>
                                                                         array(
'18' => array()
                                                                                 )
                                                            )
                                        )
                      ); 

As I said though, my attempts have failed with all kinds of unknown indexes and the like.

PHP Code:

    function recursiveBuildArray($array, &$temp)
    {
        if (isset(
$array['0']))
        {
            
$temp[$array['0']] &= array();
            
$id $array['0'];
            unset(
$array['0']);
            
$this->recursiveBuildArray($array[$id], &$temp);
        }
        else
        {
            return 
false;
        }
    } 

Any help on this one?

Salathe 05-28-2008 12:00 PM

PHP Code:

function make_multi($flat)
{
    
$multi = array();
    
$temp  =& $multi;
    foreach (
$flat as $item)
    {
        
$temp[$item] = array();
        
$temp =& $temp[$item];
    }
    return 
$multi;
}

// Quicky test
$test  = array('0''15''32''18');
$multi make_multi($test);
var_dump($multi); 


drewbee 05-28-2008 11:38 PM

Awesome, thanks mate!


All times are GMT. The time now is 11:30 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0