Reputation: 263
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.
Upvotes: 0
Views: 436
Reputation: 1275
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);
Upvotes: 3
Reputation: 656
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);
Upvotes: 2