簡體   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