Search code examples
phparraysstringusing

Php Array - String Using


i want to use array this string. How can i do this? i shared my results and strings

i used this code:

var_dump($result);

and the result returned this string:

"{
    "_": {
        "ID": "tracked"
    },
    "success": true,
    "requestTime": "2013-08-19T13:08:36-07:00",
    "test": "Sometextshere",
    "data": {
        "news": {
            "1": "Hello",
            "13": "New Text",
        },
        "date": "2013-08-19T13:08:36-07:00"
    }
}"

Solution

  • The results you've posted are JSON encoded. You first need to decode it:

    $decoded = json_decode($result);
    

    You can either return the results as an object or an array. By default it will be an object and you can retrieve the results using the point-to syntax. Say you want the string in test:

    echo $decoded->test;
    

    You can also do chained point-tos to traverse the object properties:

    echo $decoded->data->news;
    

    If you prefer to work with arrays, you can add an optional argument to your decode. Here is the same things using the array argument:

    $decoded = json_decode($result, true);
    echo $decoded['test'];
    echo $decoded['data']['news'];
    

    Hope this helps!