2

I'm trying to get into just data from

{
    "data": [{
        "media_count": 3045,
        "name": "snow",
    },
    {
        "media_count": 79,
        "name": "snowman",
    },
    {
        "media_count": 40,
        "name": "snowday",
    },
    {
        "media_count": 29,
        "name": "snowy",
    }]
}

I've been trying, using:

$obj = json_decode($res[0], true);
echo $obj['data']; //this returns an array

I also tried this:

$obj = json_encode($res[0], true);
echo $obj; // this returns json, but not inside `data`

"data": [{
"media_count":54373,
"name":"test"
}]

I just want to get inside data. How would I do so?

Thanks in advance!

UPDATE: Sorry to mention, I would like this in json format please

eventually, I would like to only see

{
    "media_count":54373,
    "name":"test"
}

Something like thiat

hellomello
  • 8,219
  • 39
  • 151
  • 297

3 Answers3

2

Use json_encode() to get what you want:

$obj = json_decode($res[0], true);
echo json_encode($obj['data']);
flowfree
  • 16,356
  • 12
  • 52
  • 76
1

In your first example, $obj['data'] returns an array because that's how the JSON is set up. According to the JSON, data is a collection of elements.

To access within the array, you can do this:

foreach($obj['data'] as $object) {
    print_r($object);
}

You can also index into it as you want:

print_r($obj['data'][0]);

EDIT

If I'm getting you correct, you want to convert the first JSON to this:

"data": [{
"media_count":54373,
"name":"test"
}]

If so, that is not possible since the second fragment is not valid JSON. (use http://jsonlint.com)

Ayush
  • 41,754
  • 51
  • 164
  • 239
  • I would like to only index into `data` so essentially, when you echo the new json, `data` shouldn't be there. – hellomello Jun 07 '12 at 05:54
  • In that case, after `json_decode` do `$obj = $obj['data']`. `$obj` now holds what you want. – Ayush Jun 07 '12 at 05:55
0

firstly access the data item of the json array;

    $obj1=$obj[item];
    $sizeobj=sizeof($obj1);

    for($i=0;$i<$sizeobj;$i++)
{
// your code to access the data items
// for eg $obj[item][$i][media_count}
}
Shiven
  • 206
  • 1
  • 9
  • 17