开发者

JSON output using PHP

开发者 https://www.devze.com 2023-03-31 09:54 出处:网络
HI i need to output a JSON object for consuming in iphone i am able to output like {\"feed\":{\"i开发者_Python百科d\":\"1\",\"player\":\"player1\"}}

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

i am able to output like

{"feed":{"i开发者_Python百科d":"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,


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));
0

精彩评论

暂无评论...
验证码 换一张
取 消