通过php将mysql数据导入json

时间:2016-04-23 06:42:14

标签: php json

我在while循环中使用json-decode。每次在.json文件中创建json代码时,它看起来如下,我无法读取.json文件。

[{"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 :(得分:0)

使用

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

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

获取关联数组。默认情况下,mysqli_fetch_array将获取关联和数字索引。