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?
任何意見讚賞。
謝謝。
你可能包括JSON輸出是不正確的? – Yhn