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

前端 未结 2 1820
我在风中等你
我在风中等你 2020-12-28 17:57

i am getting this request.   

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


        
相关标签:
2条回答
  • 2020-12-28 18:16

    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

    0 讨论(0)
  • 2020-12-28 18:29

    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

    0 讨论(0)
提交回复
热议问题