John Davidson

How to extract specific values from a list in JSON response with PHP?

0 comments
Message:


I am executing an API request, which gives a JSON response like this -



This JSON is too complex for me to work with, so I was looking for a way to eliminate useless stuff. The final JSON I would like should look somewhat like this -





Which means, I am eliminating all items except Display in the records list, and adding them all in a separate list, which just contains the display values. Is it possible to modify JSON with PHP?


Your help/advice will be very appreciated!



My Answer:
Yes, it is possible to extract specific values from a list in a JSON response using PHP. You can use the json_decode function to convert the JSON response into a PHP array, then loop through the array to extract the specific values you need.

Here is an example code snippet that demonstrates how to achieve this:

php
$jsonResponse = '{
"records": [
{
"id": 1,
"display": "Item 1"
},
{
"id": 2,
"display": "Item 2"
},
{
"id": 3,
"display": "Item 3"
}
]
}';

$data = json_decode($jsonResponse, true);

$displayValues = [];
foreach ($data['records'] as $record) {
$displayValues[] = $record['display'];
}

$finalJson = json_encode(['displayValues' => $displayValues]);

echo $finalJson;


This code will output the following JSON:


{
"displayValues": [
"Item 1",
"Item 2",
"Item 3"
]
}


You can modify this code according to your specific requirements and the structure of your JSON response.

Rate this post

3 of 5 based on 9276 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us