UnlimitedMeals
UnlimitedMeals

Reputation: 131

JSON output using PHP

HI i need to output a JSON object for consuming in iphone

i am able to output like

{"feed":{"id":"1","player":"player1"}}
{"feed":{"id":"1","player":"player2"}}
{"feed":{"id":"2","player":"player3"}}

The code :

$query = "SELECT id,player FROM MyVideos";
$result = mysql_query($query,$link) or die('Errant query: '.$query);

$players[] = array();
if(mysql_num_rows($result)){
while($player = mysql_fetch_assoc($result)){
$players[] = array('player'=>$player);
echo json_encode(array("feed"=>$player));            
}
}

But i need to output some thing like this

{"feed":
{"id":"1","player":"player1"},
{"id":"1","player":"player2"},
{"id":"2","player":"player3"}
}

Can anyone please help me with this.

Thanks,

Upvotes: 0

Views: 2666

Answers (1)

Jeremy Banks
Jeremy Banks

Reputation: 129756

The output you posted isn't valid JSON, you need to put brackets around the items in feed:

{"feed": [
    {"id":"1","player":"player1"},
    {"id":"1","player":"player2"},
    {"id":"2","player":"player3"}
]}

You should loop through your results and build an array of your feed items, and then output it all at once, like this:

$feed_items = array();

if (mysql_num_rows($result)) {
    while ($player = mysql_fetch_assoc($result)){
        $feed_items[] = $player;
    }
}

echo json_encode(array("feed" => $feed_items));

Upvotes: 7

Related Questions