2011-09-20 55 views
1

我想在AJAX請求中將MySQL查詢結果轉換爲JSON。 我的代碼目前看起來像這樣。PHP JSON編碼 - 手動分配鍵?

$offset    = empty($_GET['offset']) ? 0 : $_GET['offset']; 
$numimagestodisplay = 3;  
$items    = array(); 
$allitems   // This is the queryset obtained through a call to a function 

foreach ($allitems as $i => &$item) 
{ 
    if (($i >= $offset) && (count($items) < $numimagestodisplay)) 
    { 
     $items[$i] = $item; 
    }  
} 

$output = '{"items":'.json_encode($items).'}'; 

我然後通過在JavaScript調用上述代碼返回的結果要循環和需要通過它們的鍵來指代數組項(I需要改變使用這些值的一些HTML元素ID)。但是,JSON以錯誤的格式返回。

如果我更改線路

$items[$i] = $item; 

到:

$items[] = $item; 

然後我可以引用它的關鍵,但是關鍵是明明只是0,1,2,而我需要的鍵是循環中定義的值。

如何更改PHP代碼以正確的格式返回JSON?

任何意見讚賞。

謝謝。

+0

你可能包括JSON輸出是不正確的? – Yhn

回答

3

問題是,在Javascript(和大多數其他語言的數組)的數組不能有用戶定義的鍵。你希望你的數組被編碼爲JSON 對象而不是數組(PHP中帶有用戶定義鍵的數組本質上就是對象)。對於使用非數字鍵的數組,這通常會自動發生。

在你的情況,你可以使用JSON_FORCE_OBJECT標誌:

$output = '{"items":'.json_encode($items,JSON_FORCE_OBJECT).'}'; 

documentation

Non-associative array output as array: [[1,2,3]] 
Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}