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

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

i am getting this request.   

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


        
2条回答
  •  一个人的身影
    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'].'
    '; }

    Output:

    kothrud
    katraj
    

    Update #2:

    for that true:

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

提交回复
热议问题