2013-07-09 155 views
-1

首先,請看看這個JSON http://ws.luyencong.net/data/search/query.php?do=json只返回一個對象JSON而不是多個對象PHP?

下面是它的代碼:

/* --- 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

幫助將不勝感激。感謝任何事情。

祝您有美好的一天!

+0

所以你希望我們告訴你用[]包裝你的JSON? :) –

+0

請包括一個簡單的例子:現在如何看待輸出,應該怎麼看。鏈接的輸出是不可讀的。 – matino

+1

你想要一個json散列,其中有像'B \ u1ed1 c \ u00e1o th \ u00e0nh l \ u1eadp di \ ueec5n \ u0111 \ u00e0n Luy \ c7n C \ u00f4ng'? – miah

回答

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

但爲什麼地獄的關鍵是價值相同?不應該是數組('subject'=> $ data ['subject']); – steven

+0

@steven只有op會知道肯定.. – Orangepill

+1

你的答案不會重新格式化JSON,因爲OP已經問了。 – Schleis

1

您正在嵌套您的陣列。看起來你只想擁有一個JSON對象而不是它們的數組。因此,改變你的$result的設置是:

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

然後作爲建議移動json_encode之外循環的,你不需要做,直到陣列已被填充後。你只是無緣無故地重複覆蓋變量。

相關問題