0

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!

1
  • Are all the ids included in a single string like "01, 01/01,01/03/05/05" ? Show how those ids presented in your current code Commented Jun 2, 2016 at 11:41

1 Answer 1

1

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
}
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.