php json_encode is encoding the same data twice

后端 未结 3 1881
长情又很酷
长情又很酷 2021-01-02 16:32

I am getting some data from a database and am encoding it to json:

$json = \"\";
if($result = $dbc->query($query)) {
    $num = $result->num_rows;
             


        
相关标签:
3条回答
  • 2021-01-02 16:42

    Pekka is probably right, but I would like to add that you are making more work for yourself by calling json_encode() for every row. It's probably better to build your data structure, and then call json_encode() on that:

    $rows = array();
    if ($result = $dbc->query($query)) {
        $num = $result->num_rows;
        for ($i = 0; $i < $num; $i++) {
            $rows[] = $result->fetch_assoc();
        }
    }
    $json = json_encode($rows);
    

    Marking as community wiki as this is a suggestion on practice and not an answer.

    0 讨论(0)
  • 2021-01-02 16:44

    This is because you are using fetch_array() (emphasis mine):

    mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.

    Use fetch_assoc() instead.

    0 讨论(0)
  • 2021-01-02 16:55

    Just change $row = $result->fetch_array(); to $row = $result->fetch_assoc();

    0 讨论(0)
提交回复
热议问题