简体   繁体   中英

PHP multidimensional array - Search value using key

I have an array generated out of json_decode(). $array_data = json_decode(json_encode(simplexml_load_string($data)), true);

The output array looks like below:

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
                                        )

                                )

                        )

                )

        )

)

I need to save the value of the key 'workorderid' in another php varaible,so I can use it further in my code. the value is dynamic.

I have been struggling a lot now and looking for some guidance. Could anyone please help with out in getting this done? Thanks a lot in advance!

Regards, Pooja

If you know for sure the first array under Details will contain the workorderid key, you can just access it directly:

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

var_dump($workorderid);

Output:

string(6) "291885"


If you don't know in which array under Details it will be, you'll have to loop over it and find it:

$workorderid = null;

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

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

Output:

string(6) "291885"

This is a viable solution if you only need to fetch 1 key from the response. If you'd need more keys I'd suggest mapping the response data into a more readable structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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