从数据库获取数组到json_encode

时间:2016-04-25 13:43:39

标签: javascript php

我试图展示这样的数组(显示id_suppliernama_supplier

{"1":"PT Kesatu","2":"PT Kedua","3":"PT Ketiga","4":"PT Keempat"}

来自supplier表。我使用了以下代码:

$query = mysql_query("SELECT id_supplier, nama_supplier FROM supplier ORDER BY nama_supplier");  
$supplier = array();
while($row = mysql_fetch_object($query)){
$supplier = $row;
}
echo json_encode($supplier);

但它只是向我显示了1条记录,结果就像这样

{"id_supplier":"5","nama_supplier":"PT Unggas Makmur"}

3 个答案:

答案 0 :(得分:1)

这将是:

while($row = mysql_fetch_object($query)){
$supplier[] = $row; // not only $supplier - [] will automatically increment the index
}

答案 1 :(得分:1)

使用[]数组。

$query = mysql_query("SELECT id_supplier, nama_supplier FROM supplier ORDER BY nama_supplier");  
$supplier = array();
while($row = mysql_fetch_object($query)){
$supplier[] = $row;
}
echo json_encode($supplier);

答案 2 :(得分:0)

您需要使用[]数组:

$query = mysql_query("SELECT id_supplier, nama_supplier FROM supplier ORDER BY nama_supplier");  
$supplier = array();
while($row = mysql_fetch_object($query)){
$supplier[] = $row; // not only $supplier ,but [] will increment, and get all the values
}
echo json_encode($supplier);