jeudi 24 mai 2018

PHP How to get a particular JSON values/parameter

This is my JSON Response came from an URL API. I use GuzzleHttp\Client and json_decode() inorder to manage.

[{
    "INDEX_ID": "0",
    "NOTES": "0; Farming"
},
{
    "INDEX_ID": "1",
    "NOTES": "Fruit Name; List of Fruits;"
},
{
    "INDEX_ID": "2",
    "NOTES": "Apple"
},
{
    "INDEX_ID": "3",
    "NOTES": "Orange"
},
{
    "INDEX_ID": "4",
    "NOTES": "Grapes"
},
{
    "INDEX_ID": "5",
    "NOTES": "Mango"
},
{
    "INDEX_ID": "6",
    "NOTES": "Animal Name; List of Animal;"
},
{
    "INDEX_ID": "7",
    "NOTES": "Pig"
},
{
    "INDEX_ID": "8",
    "NOTES": "Goat"
},
{
    "INDEX_ID": "9",
    "NOTES": "Cow"
}]

But I only need to save list of Fruits in my logfile. Can someone help me how to exclude the other json parameters and get only the particular json parameters using foreach loop or any method inorder to get that result.

I just want it to be like this:

[
{
    "NOTE_NO." : "001",
    "CATEGORY" : "FRUITS",
    "LISTS_TO_BUY" : [
    {
        "FRUITS": "Apple"
    },
    {
        "FRUITS": "Orange"
    },
    {
        "FRUITS": "Grapes"
    },
    {
        "FRUITS": "Mango"
    }
    ]
 }
 ]

He're my codes so far:

        $response_body = json_decode($json_response, true);
        $json_new_param = [];

        foreach ($response_body as $value) {
            $json_new_param[] = [
                'FRUITS' => $value['NOTES']
            ];
        }
        $header = [
            [
                'NOTE_NO.' => '001',
                'CATEGORY' => 'FRUITS',
                'LISTS_TO_BUY' => $json_new_param
            ]
        ];
        echo json_encode($header);

$json_response is the response given above.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire