繁体   English   中英

PHP多维数组 - 使用键搜索值

[英]PHP multidimensional array - Search value using key

我有一个由json_decode()生成的数组。 $ array_data = json_decode(json_encode(simplexml_load_string($ data)),true);

输出数组如下所示:

Array
(
    [@attributes] => Array
        (
            [version] => 1.0
        )

    [response] => Array
        (
            [operation] => Array
                (
                    [@attributes] => Array
                        (
                            [name] => ADD_REQUEST
                        )

                    [result] => Array
                        (
                            [statuscode] => 200
                            [status] => Success
                            [message] => Request added successfully
                        )

                    [Details] => Array
                        (
                            [0] => Array
                                (
                                    [workorderid] => 291885
                                )

                            [1] => Array
                                (
                                    [parameter] => Array
                                        (
                                            [name] => workorderid
                                            [value] => 291885
                                        )

                                )

                        )

                )

        )

)

我需要在另一个php变量中保存键'workorderid'的值,所以我可以在我的代码中进一步使用它。 价值是动态的。

我现在一直在苦苦挣扎并寻找一些指导。 有人可以帮忙完成这项工作吗? 非常感谢提前!

此致,Pooja

如果您确定Details下的第一个数组将包含workorderid键,您可以直接访问它:

$workorderid = $array_data['response']['operation']['Details'][0]['workorderid'];

var_dump($workorderid);

输出:

string(6)“291885”


如果你不知道它将在Details下面的哪个数组,你将不得不循环它并找到它:

$workorderid = null;

foreach ($array_data['response']['operation']['Details'] as $detail) {
    if (isset($detail['workorderid'])) {
        $workorderid = $detail['workorderid'];
        break;
    }
}

if (null !== $workorderid) {
    var_dump($workorderid);
}

输出:

string(6)“291885”

如果您只需要从响应中获取1个密钥,这是一个可行的解决方案。 如果您需要更多密钥,我建议将响应数据映射到更易读的结构中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM