在PHP中的Array上以JSON格式输出数据

时间:2012-01-09 01:47:31

标签: php json

$result = mysql_query($query);
$leaderboard = array();

while($row = mysql_fetch_assoc($result)) {
    $leaderboard[$row["username"]] = $row["score"];
}

$output = array
(
    'status' => 1,
    'content' =>$leaderboard
);

print_r(json_encode($output));

现在$output数组就是这样的JSON:

{"tim":"120","john":"45","larry":"56"}

但我希望将它们作为键值对,所以我想要像:

{"name":"tim","score":120","name":"john","score="45", etc.}

如果我需要这样,我如何修改$leaderboard数组,以便输出就像那样?

1 个答案:

答案 0 :(得分:5)

$leaderboard[] = Array('name' => $row["username"], 'score' => $row["score"]);