I have a json string i which has a object in one one there is one json array & another object i want to first the json array then convert into php array & other json object into the php variable.Please tell me how to do this. I have stdclass but i am not able to get accurate data.
Json String
{
    "data": [
    {
        "ques_name": "no",
        "ques_id": "1"
    }, {
        "ques_name": "yes",
        "ques_id": "2"
    }, {
        "ques_name": "no",
        "ques_id": "3"
    }, {
        "ques_name": "yes",
        "ques_id": "4"
    }, {
        "ques_name": "no",
        "ques_id": "5"
    }, {
        "ques_name": "yes",
        "ques_id": "6"
    }, {
        "ques_name": "no",
        "ques_id": "7"
    }
    ],
    "UserId": 163
}
I used following code to get the array but it gives me array of size 14 where as size should be 7
    $params=$_GET['params'];
    $arr=array();
    $decode=json_decode($params);
    $arr=$decode->data;
    print_r($arr);
                json_decode($array) will convert your json object into an array.
Edit:
you can try json_decode($array, true);. That way returned objects will be converted into associative arrays.
Edit2: using my code in edit section (json_decode($array, true);), i get the following array (which seems ok to me):
Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [ques_name] => no
                    [ques_id] => 1
                )
            [1] => Array
                (
                    [ques_name] => yes
                    [ques_id] => 2
                )
            [2] => Array
                (
                    [ques_name] => no
                    [ques_id] => 3
                )
            [3] => Array
                (
                    [ques_name] => yes
                    [ques_id] => 4
                )
            [4] => Array
                (
                    [ques_name] => no
                    [ques_id] => 5
                )
            [5] => Array
                (
                    [ques_name] => yes
                    [ques_id] => 6
                )
            [6] => Array
                (
                    [ques_name] => no
                    [ques_id] => 7
                )
        )
    [UserId] => 163
)
Edit3: for what you ask on how to get the id/name part of the array, here is a small example code:
$jsonData= ''; // put here your json object
$arrayData = json_decode($jsonData, true);
if (isset($arrayData['data']))
{
foreach ($arrayData['data'] as $data)
{
echo 'id='.$data['ques_id'].', name='.$data['ques_name'].'<br>';
}
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With