简体   繁体   中英

Nested array in json data in php

I need to show Mysql data in json nested array like

{
    "status": true,
    "categories": [
        {
            "id": "1",
            "title": "Title 1",
        },
        {
            "id": "2",
            "title": "Title 2",
        },
        {
            "id": "3",
            "title": "Title 3",
        }
    ]
}

Code I am trying is

$sql = "SELECT * FROM `categories`";
$res_data = mysqli_query($conn,$sql);
$rows = array();
while($row = mysqli_fetch_array($res_data)){
    $rows[] = $row;
    foreach($rows as $row){
        $rows = ['id' => $row['id'], 'title' => $row['title']];             
    }
}

    
    $data = array('status' => true, 'categories' => array($rows));
    echo json_encode($data);

But what I get is only with one record in the nested array ie

{
    "status": true,
    "categories": [
        {
            "id": "1",
            "title": "Title 1",
        }
    ]
}

How can I achieve my requirement?

If you want to avoid duplication, leave out the foreach loop and just write in the while loop:

$rows[] = ['id' => $ row ['id'], 'title' => $ row ['title']];

…because with the while loop, you already run through the row array.

You don't need any loops. Mysqli already returns a nested array which you can directly output to JSON

$res_data = $conn->query("SELECT id, title FROM `categories`")

echo json_encode(['status' => true, 'categories' => $res_data->fetch_all(MYSQLI_ASSOC)]);

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