2016-04-25 52 views
-1

我试图表现出这样的阵列(显示id_suppliernama_supplier数组json_encode

{"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"} 
+2

不要使用'mysql_ *'功能,它们被弃用的PHP 5.5,并且在PHP 7.0完全删除。使用['mysqli'](http://php.net/manual/en/book.mysqli.php)或['pdo'](http://php.net/manual/en/book.pdo.php)代替。 [这就是为什么你不应该使用'mysql_ *'函数](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)。 –

回答

1

这将是:

while($row = mysql_fetch_object($query)){ 
$supplier[] = $row; // not only $supplier - [] will automatically increment the index 
} 
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); 
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); 
+0

这是如何改善已提供的答案的? – YvesLeBorg

+0

@YvesLeBorg,我想你没有检查过。两个答案几乎同时发生,没有时差。在采取任何行动之前,你应该先看过它 – Nehal

+0

不幸的是,我没有'检查'...虽然现在没有人能够看到它,但是两分钟之后,其他答案都会与你相聚。 – YvesLeBorg