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

1
  • Btw, your original JSON, as it stands, is not valid due to the trailing commas. Commented Jun 7, 2012 at 5:58

3 Answers 3

2

Use json_encode() to get what you want:

$obj = json_decode($res[0], true);
echo json_encode($obj['data']);
Sign up to request clarification or add additional context in comments.

Comments

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)

2 Comments

I would like to only index into data so essentially, when you echo the new json, data shouldn't be there.
In that case, after json_decode do $obj = $obj['data']. $obj now holds what you want.
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}
}

2 Comments

So if I try $obj1 = $obj['data'], I get this "
$obj1 is not access it is just to find the size of the 'data'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.