我使用json _encode()
傳遞db值。以下是查詢和所有作品沒關係。獲取沒有索引號的json_encode數據
但是,當我向陣列添加一個額外的數據時,我在輸出數據前面得到一個數字。
$sql = "SELECT item, price, availability
FROM items
WHERE category = :category
ORDER BY item DESC";
$stmt= $connect->prepare($sql);
$stmt->execute(array(':category'=>"fruits"));
$rslt = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rslt as $val){
$data[] = $val;
}
$data['additional'] = $someAdditionalData;
echo json_encode($data);
電流輸出:
{"0":{"item":"lychee"},"1":{"item":"ornage"},"2": "item":"apple"},"additional":ABC}
我的問題是,我怎麼沒有索引號的輸出(如下)
[{"item":"lychee"},{"item":"ornage"},{"item":"apple"},{"additional":"ABC"}]
只需放下'foreach()'循環,你就可以擁有它。 – Havelock
@Havelock謝謝。我用'$ data [] = $ rslt;'替換了'foreach()'循環,但是這不會給我預期的輸出? – Becky