Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an array like a one way list:

array(
    'data1' => <some data>,
    'next' => array(
        'data2' => <some data>,
        'next' => array(
            'data3' => <some data>,
            'next' => array(
                'data4' => <some data>,
                'next' => array(
                    'data5' => <some data>,
                    'next' => ..... etc to data n
                );
            );
        );
    );
);

I need to get data from inside arrays in reverse order. (data n, ... , data 2, data 1) Do You know any nice method for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
677 views
Welcome To Ask or Share your Answers For Others

1 Answer

You're not looking for the reverse of the array, but you're looking for something reverse.

Getting a better understanding first of the kind of reverse might help you.

You need the parent of each individual element. The parent is always the previous one if you traverse on next. So if you add the previous one as the parent, then the last element of the array is the one you're looking for.

So sounds straight forward. The harder part is to express this with so called variable aliasing / references.

Let's add all the parents and while traversing the array, removing the 'next' entry after referencing it:

/* traverse the path on 'next' and keep previous to set 'parent' of current */
$walk = &$array; // start at root node
while ($walk) {

    if (isset($previous)) {
        $walk['parent'] = &$previous;
    }

    $previous = &$walk;

    $hasNext = array_key_exists('next', $walk);
    if ($hasNext) {
        $walk = &$walk['next'];
        unset($previous['next']);
    } else {
        break;
    }
}
unset($previous);

As written the last element then would contain the array you're looking for. That last element is $walk here:

print_r($walk);

Which gives you (Demo):

Array
(
    [data5] => <some data5>
    [parent] => Array
        (
            [data4] => <some data4>
            [parent] => Array
                (
                    [data3] => <some data3>
                    [parent] => Array
                        (
                            [data2] => <some data2>
                            [parent] => Array
                                (
                                    [data1] => <some data1>
                                )
    ...
)

Hope this is helpful and understandable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...