-1

首先,请看一下这个 JSON http://ws.luyancong.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.luyancong.net/data/search/json.txt

帮助将不胜感激。感谢一切。

祝你有美好的一天!

4

3 回答 3

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);
于 2013-07-09T14:41:53.413 回答
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;
于 2013-07-09T14:42:19.823 回答
1

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

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

然后按照建议移动json_encode循环外部,直到填充数组之后才需要这样做。您只是无缘无故地一遍又一遍地覆盖变量。

于 2013-07-09T14:44:57.397 回答