How to send an array of objects in JSON format from PHP

后端 未结 6 2101
一向
一向 2020-12-31 12:59

New to php. I am trying to send JSON data to front end in name-value pair. I tried an example which I got here The following is my code fragment which sends the data in JSO

6条回答
  •  生来不讨喜
    2020-12-31 13:24

    $list needs to be an array, and you can just push items to it like in this code:

    $list = array();
    while($stmt->fetch()){
        $list[] = array('id' => $fid, 'name' => $fname);
    }
    $stmt->free_result();
    $stmt->close();
    echo json_encode($list);
    

    You could also use the method fetch_all() to get all rows at once, instead of iterating with a loop. Although in this example you'd get all fields that you've selected, instead of just id and name.

    $list = $stmt->fetch_all();
    $stmt->free_result();
    $stmt->close();
    echo json_encode($list);
    

提交回复
热议问题