从相反的顺序单向阵列获取数据 [英] Getting data from one way array in reverse order

查看:95
本文介绍了从相反的顺序单向阵列获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个方式列表中的数组:

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
                );
            );
        );
    );
);

我需要以相反的顺序从内阵列的数据。 (数据n,...,数据2,数据1)你知道这个漂亮的任何方法?

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?

推荐答案

您不是在寻找数组的反向,但你正在寻找的的东西扭转

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.

您需要各个元素的父元素。家长总是previous之一,如果你对穿越的下次的。所以,如果你添加previous一个作为父母,则数组的最后一个元素就是你要找的人。

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.

所以听起来直截了当。更难的部分是前preSS这跟所谓的可变别名/引用。

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);

它给你(演示):

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.

这篇关于从相反的顺序单向阵列获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆