简体   繁体   中英

PHP - How to get key values from a dynamic JSON response

I have a JSON response and my code needs to pull out key values if a certain value exist.

For example.

If this title exist, then display it's key value etc.

Here's my JSON package:

{
    "Data": {
        "Rows": [{
            "Title": "Economy Road",
            "ServiceType": "6. Economy Road (Pallets)",
            "GrandPrice": 14.50
        }, {
            "Title": "Road Freight",
            "ServiceType": "1. Road Freight",
            "GrandPrice": 16.50
        }, {
            "Title": "Home Delivery",
            "ServiceType": "Platinum",
            "GrandPrice": 10.50
        }]
    }
}

How would I loop through this JSON data and display the GrandPrice if it matches the ServiceType?

For example, if ServiceType = "1. Road Freight" then display GrandPrice of 16.50 etc.

I also tried to decode the json data and pull out the key value using a fixed index number like so:

$data_result_json_decoded->Data->Rows[1]->ServiceType;

However this JSON response is not fixed and is dynamic.

Any help would greatly be appreciated.

You can Utilize array_search to search by value and array_column to get a single column to compare and perform search inside an array

// set Array to search
$rows = $data_result_json_decoded->Data->Rows;

// String to search
$string = "1. Road Freight";
// get ServiceType array
$array_that_only_contains_ServiceType = array_column($rows, "ServiceType");
// First seach key
$key = array_search($string, $array_that_only_contains_ServiceType);

// get data from search key
$data = $rows[$key];

var_dump($data);

You need to iterate inside the [Data]['Rows'] array to get the rows filtered. Here I have taken the ServiceType matched rows in the result array.

$json = '{
    "Data": {
        "Rows": [{
            "Title": "Economy Road",
            "ServiceType": "6. Economy Road (Pallets)",
            "GrandPrice": 14.50
        }, {
            "Title": "Road Freight",
            "ServiceType": "1. Road Freight",
            "GrandPrice": 16.50
        }, {
            "Title": "Home Delivery",
            "ServiceType": "Platinum",
            "GrandPrice": 10.50
        }]
    }
}';
$data = json_decode( $json, true );
$search = '1. Road Freight';
$result = [];

foreach ($data['Data']['Rows'] as $item) {
    if( $item['ServiceType'] == $search ){
        $result [] = $item;
      //you can also echo here as you wanted
        echo $item['GrandPrice'];
    }
}

var_dump($result);

Run Here

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