Quick JSON/PHP question

Discussion in 'PHP' started by nonee, Oct 17, 2008.

  1. #1
    Thanks guys. My problem now is parsing multiple JSON strings.
    Here's what the JSON is:

    {
        "songs": [
            {
                "by": "artist",
                "cover": "albumart",
                "id": 1,
                "rank": 1,
                "title": "song name",
                "type": "song"
            },
            {
                "by": "artist1",
                "cover": "albumart1",
                "id": 2,
                "rank": 2,
                "title": "song name1",
                "type": "song"
            }
        ]
    }
    
    Code (markup):
    I can parse single entries but as soon as it has two the page goes blank. I have tried using a for each loop with JSON decode but it only works when there is one.
    Here is the parser that doesn't work:
    
    $json = '{
        "songs": [
            {
                "by": "artist",
                "cover": "albumart",
                "id": 1,
                "rank": 1,
                "title": "song name",
                "type": "song"
            },
            {
                "by": "artist1",
                "cover": "albumart1",
                "id": 2,
                "rank": 2,
                "title": "song name1",
                "type": "song"
            }
        ]
    }';
    $obj = json_decode($json);
    foreach($obj->{'by'} as $val){
        echo $val;
        }
    
    Code (markup):
    Any help is greatly appreciated
     
    nonee, Oct 17, 2008 IP
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #2
    ok, you aren't quite grasping how the JSON output is indexed here. Your foreach is returning the object which contains a 'songs' object. You need to index the object by each 'song', then echo out that song's 'by' object.

    $obj=json_decode($json);
    foreach ($obj->songs as $song) {
      echo $song->by;
    }
    Code (markup):
    I think that's what you are trying to do. Been a while since I've dealt with JSON though.
     
    deathshadow, Oct 18, 2008 IP