RayZorPL
RayZorPL

Reputation: 21

Exploding String to multidimensional associative array

I need to convert people ID's to an associative array. The id's can look like that:

"01"
"01/01"
"01/03/05/05"
etc.

Now I need to put it into an array so I can get to it like this:

$array['01']  
$array['01']['01']  
$array['01']['03']['05']['05']

Any ideas? Thank you in advance!

Upvotes: 0

Views: 127

Answers (1)

iainn
iainn

Reputation: 17417

This is always a bit of a tricky one to work out the first time. The key is to create a reference variable to your resulting array, and move it down through the tree as you parse each step.

<?php
$paths = [
    '01',
    '01/01',
    '01/03/05/05',
];

$array = []; // Our resulting array
$_     = null; // We'll use this as our reference

foreach ($paths as $path)
{
    // Each path begins at the "top" of the array
    $_ =& $array;

    // Break each path apart into "steps"
    $steps = explode('/', $path);

    while ($step = array_shift($steps))
    {
        // If this portion of the path hasn't been seen before, initialise it
        if (!isset($_[$step])) { $_[$step] = []; }

        // Set the pointer to the new level of the path, so that subsequent
        // steps are created underneath
        $_ =& $_[$step];
    }
}

=

array (1) [
    '01' => array (2) [
        '01' => array (0)
        '03' => array (1) [
            '05' => array (1) [
                '05' => array (0)
            ]
        ]
    ]
]

You can then test for an element's existence using isset, e.g.

if (isset($array['01']['03']['05']['05']))
{
    // do stuff
}

Upvotes: 1

Related Questions