Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Decode Json object in laravel and apply foreach loop on that in laravel

Tags:

json

php

laravel

i am getting this request.   

 { "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

and i want to provide response to this by searching records in database based on above request. how will i decode above json array and use each area field separately.

like image 866
Parag Bhingre Avatar asked Mar 16 '15 06:03

Parag Bhingre


2 Answers

your string is NOT a valid json to start with.

a valid json will be,

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

if you do a json_decode, it will yield,

stdClass Object
(
    [area] => Array
        (
            [0] => stdClass Object
                (
                    [area] => kothrud
                )

            [1] => stdClass Object
                (
                    [area] => katraj
                )

        )

)

Update: to use

$string = '

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

';
            $area = json_decode($string, true);

            foreach($area['area'] as $i => $v)
            {
                echo $v['area'].'<br/>';
            }

Output:

kothrud
katraj

Update #2:

for that true:

When TRUE, returned objects will be converted into associative arrays. for more information, click here

like image 62
itachi Avatar answered Sep 18 '22 14:09

itachi


you can use json_decode function

foreach (json_decode($response) as $area)
{
 print_r($area); // this is your area from json response
}

See this fiddle

like image 34
Kamran Avatar answered Sep 18 '22 14:09

Kamran