2016-04-23 73 views
-1

我使用while循環中的JSON解碼。每次它在.json文件中創建json代碼時,它看起來像下面,我無法讀取此.json文件。MySQL數據爲JSON通過PHP

[{"0":"2","id":"2","1":"avss","productname":"avss","2":"2920","price":"2920","3":"xasx","textarea":"xasx","4":"e3.jpg","name":"e3.jpg","5":"uploads\/e3.jpg","imagepath":"uploads\/e3.jpg"}] 

我希望它是這樣的......

[ 
    { 
     "id": 0, 
     "name": "Item 0", 
     "price": "$0" 
    }, 
    { 
     "id": 1, 
     "name": "Item 1", 
     "price": "$1" 
    }, 
    { 
     "id": 2, 
     "name": "Item 2", 
     "price": "$2" 
    }, 
    { 
     "id": 3, 
     "name": "Item 3", 
     "price": "$3" 
    }, 
    { 
     "id": 4, 
     "name": "Item 4", 
     "price": "$4" 
    }, 
    { 
     "id": 5, 
     "name": "Item 5", 
     "price": "$5" 
    }, 
    { 
     "id": 6, 
     "name": "Item 6", 
     "price": "$6" 
    } 
] 

代碼:

global $connection; 
$sql = "SELECT * FROM `forms`"; 
$mq = mysqli_query($connection,$sql); 

while($row = mysqli_fetch_array($mq)){ 
      echo '<div class="form-group"><img src="'.$row['imagepath'].'" alt="HTML5 Icon" style="width:250px;height:180px">&nbsp '.    
      $row['name']."".$row['price'].'</div>'; 



    $emparray = array(); 
    $emparray[] = $row; 
    $fp = fopen('tables/data.json', 'w'); 
    $k= json_encode($emparray); 

    fwrite($fp,$k); 
    fclose($fp); 
+1

你的代碼在哪裏? –

+0

while($ row = mysqli_fetch_array($ mq)){'? – Barmar

+0

您每次在循環中都清空'$ emparray()'。你應該在**循環之前初始化**,在循環內添加到數組**,並將其轉換爲JSON並在循環後寫入文件**。這是簡單的邏輯。 – Barmar

回答

0

使用

while($row = mysqli_fetch_array($mq, MYSQLI_ASSOC)) { 

while($row = mysqli_fetch_assoc($mq)) { 

抓取關聯數組。默認情況下,mysqli_fetch_array將獲取關聯和數字索引。