如何以JSON格式编码mysql数据?

时间:2018-08-18 08:28:51

标签: php json

代码:

<?php
    session_start();
    error_reporting(0);
    include("config.php");
    $sql = "select * from category";
    $result = mysqli_query($con,$sql);
    while($row = mysqli_fetch_array($result))
    {
        $data[] = array(
                        'category' => $row['category_name'],
                        'image' => $row['file_s']
                    );
    } 
    echo json_encode($data);
?>

在此代码中,我已使用json_encode函数将json格式的mysql数据转换为。它显示如下:

[
  {
    "category": "cap",
    "image": "Cap-01.png"
  },
  {
    "category": "hair",
    "image": "Hair Color-01.png"
  }
]

但是我想要另一种方式:

[
cap  {
       "image": "Cap-01.png"
     },
hair {
       "image": "Hair Color-01.png"
     }
]

那我该怎么做呢?请帮助我。

谢谢

1 个答案:

答案 0 :(得分:1)

使用类别名称作为索引

while ($row = mysqli_fetch_array($result)) {
    $data[$row['category_name']] = array(
        'image' => $row['file_s']
    );
}
echo json_encode($data);