在不知道父元素的情况下访问多维数组元素 [英] Access Multidimensional Array element with out knowing parent elements

查看:66
本文介绍了在不知道父元素的情况下访问多维数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有返回以下多维数组的函数.我无法控制数组的形成方式.我试图访问结果"元素.这个问题是,父元素的名称不断变化. 结果"元素的位置始终相同(因为名称为结果").是否可以在不知道父元素名称的情况下访问该元素?

    Array
(
    [sHeader] => Array
        (
            [aAction] => ActionHere
        )

[sBody] => Array
    (
        [CreatePropertyResponse] => Array
            (
                [CreatePropertyResult] => Array
                    (
                        [Message] => Successfully completed the operation
                        [Result] => 0
                        [TransactionDate] => 2013-05-19T21:54:35.765625Z
                        [bPropertyId] => 103
                    )

            )

    )

)

解决方案

一个简单的递归搜索数组键/值的方法是使用递归迭代器.这些是内置类,是标准PHP库的一部分.

$result   = false;
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $key => $value) {
    if ($key === 'Result') {
        $result = $value;
        break;
    }
}

var_dump($result);

这里的好处是,您可以根据需要检查数组结构中Result项($iterator->getDepth())的深度和/或检查一个或多个祖先键($iterator->getSubIterator(…)->key()). /p>

I have function that returns the following multidimensional array. I don't have control of how the array is formed. Im trying to access the 'Result' elements. This issue is, the name of the parent elements constantly changing. The location of the 'Result' element is always the same (as the is the name "Result"). Is it possible to access that element without know the name of the parent elements?

    Array
(
    [sHeader] => Array
        (
            [aAction] => ActionHere
        )

[sBody] => Array
    (
        [CreatePropertyResponse] => Array
            (
                [CreatePropertyResult] => Array
                    (
                        [Message] => Successfully completed the operation
                        [Result] => 0
                        [TransactionDate] => 2013-05-19T21:54:35.765625Z
                        [bPropertyId] => 103
                    )

            )

    )

)

解决方案

An easy option to search the array keys/values recursively is to use a recursive iterator; these are built-in classes, part of the Standard PHP Library.

$result   = false;
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $key => $value) {
    if ($key === 'Result') {
        $result = $value;
        break;
    }
}

var_dump($result);

The bonus here is that you could, if you wanted to, check the depth of the Result item ($iterator->getDepth()) in the array structure and/or check one or more ancestor keys ($iterator->getSubIterator(…)->key()).

这篇关于在不知道父元素的情况下访问多维数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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