0

I am able to traverse a multi-dimensional array, but I also need information about dependencies. Here is what I am trying to do. I have an array like this:

array(
    'top1' => 'sth',
    'top2' => array(
        'sub1' => 'sth',
        'sub2' => array(
            'line1' => 'sth',
            'line2' => 'sth'
        )
    )
    'top3' => 'sth'
)

I am able to traverse the array to get all the keys, result is this:

array([0] => 'top1', [1] => 'top2', [2] => 'sub1', [3] => 'sub2', ...)

However, I need to know the parent of the current element. So I hope I could get something like this:

array(
    [top1] => array('parent' => 0, 'id' => 1),
    [top2] => array('parent' => 0, 'id' => 2),
    [sub1] => array('parent' => 2, 'id' => 2.1),
    [sub2] => array('parent' => 2, 'id' => 2.2),
    [line1] => array('parent' => 2.2, 'id' => 2.2.1),
    ...
    [top3] => array('parent' => 0, 'id' => 3)
)

I have been trying many ways, but couldn't always get the correct result. Can anyone solve this out? Thanks!

1
  • What is your code to get the flat array? Commented Oct 3, 2012 at 12:52

1 Answer 1

1

here is a working example for you

function traverse(array $input, $parent = null) {

    $result = array();
    $current = 1;
    foreach ($input as $key => $value) {

        $id = null !== $parent ? $parent . '.' . $current : $current;
        $result[$key] = array('parent' => null !== $parent ? $parent : 0, 'id' => $id);
        if (is_array($value)) {

            $result = array_merge($result, traverse($value, $id));
        }

        $current++;
    }

    return $result;
}

$input = array(
    'top1' => 'sth',
    'top2' => array(
        'sub1' => 'sth',
        'sub2' => array(
            'line1' => 'sth',
            'line2' => 'sth'
        )
    ),
    'top3' => 'sth'
);

echo '<pre>';
print_r($input);
echo '<hr>';
print_r(traverse($input));
echo '</pre>';
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.