18

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.

2
  • Please post your work on it. Commented Mar 16, 2015 at 6:56
  • your json is invalid Commented Mar 16, 2015 at 7:25

2 Answers 2

39

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

Sign up to request clarification or add additional context in comments.

3 Comments

i don't know how to get that json array in variable.i am sending that area array from postman rest client to webservice.i don't know how to get that array in variable and use it.
can you tell me what is ($string,true)
if that json $string array is in different view then how to bring it in controller's particular function in laravel.
10

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

5 Comments

but how area array will Come into json $response. I am using Postman rest client for web services and from there only i am getting array area. but i do not know how to access it in my code.
i tried but it is giving me Undefined variable: response error
are you using curl to get data from web service in your php code ?
@ParagBhingre post what you are trying
if that json $string array is in different view then how to bring it in controller's particular function in laravel. your suggestion is correct.But my $json is coming from web services so i dont know how to bring that $json in controller's particular function. In core php it is perfectly working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.