简体   繁体   中英

How to encode mysql data in JSON format?

code:

<?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);
?>

In this code I have convert mysql data in json format using json_encode function. It display look like as below:

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

But I want it another way like:

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

So how can I do this? Please help me.

Thank You

use category name as index

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM