PHP只返回一个对象JSON而不是多个对象?

时间:2013-07-09 14:35:57

标签: php json

首先,请看一下这个JSON http://ws.luyencong.net/data/search/query.php?do=json

这是代码:

/* --- Execute query and get the data. --- */
$query = $db->query("SELECT t.* FROM ".TABLE_PREFIX."threads t");
while($data = $db->fetch_array($query))
{
    $results[] = array($data['subject'] => $data['subject']);
    $json = json_encode($results, JSON_FORCE_OBJECT);
}

/* --- Print the results to the screen, for future purposes. --- */
echo $json;

但我希望输出JSON格式如下所示:http://ws.luyencong.net/data/search/json.txt

帮助将不胜感激。谢谢。

祝你有个美好的一天!

3 个答案:

答案 0 :(得分:4)

我相信你只想改变这个:

$results[] = array($data['subject'] => $data['subject']);

对此:

$results[$data['subject']] = $data['subject'];

并且,正如@Orangepill建议的那样,将json_encode调用移出循环。所以你的整个解决方案看起来像这样:

/* --- Execute query and get the data. --- */
$query = $db->query("SELECT t.* FROM ".TABLE_PREFIX."threads t");
$results = array();
while($data = $db->fetch_array($query))
{
    $results[$data['subject']] = $data['subject'];
}

/* --- Print the results to the screen, for future purposes. --- */
echo json_encode($results, JSON_FORCE_OBJECT);

答案 1 :(得分:2)

你必须在循环之外移动你的json_encode调用。

/* --- Execute query and get the data. --- */
$query = $db->query("SELECT t.* FROM ".TABLE_PREFIX."threads t");
while($data = $db->fetch_array($query))
{
    $results[$data['subject']] = $data['subject'];
}
$json = json_encode($results, JSON_FORCE_OBJECT);
/* --- Print the results to the screen, for future purposes. --- */
echo $json;

答案 2 :(得分:1)

您正在嵌套数组。看起来你只想拥有一个JSON对象而不是它们的数组。因此,请将$result的设置更改为:

$results[$data['subject']] = $data['subject'];

然后按照建议将json_encode移到循环之外,在填充数组之前不需要这样做。你只是无缘无故地一遍又一遍地覆盖变量。