PHP encode JSON (2 dimensional array)

后端 未结 1 1948
梦如初夏
梦如初夏 2020-12-21 14:03

I am querying a table that return to fields(message_type & percentage). I use PHP to encode the json data, here is how i do it

$json = array();
while ($r         


        
相关标签:
1条回答
  • 2020-12-21 14:56

    PHP's json_encode() uses a certain amount of magic to determine whether a given vector is encoded as a JSON object or an array, but the simple rule is this: If the array has contiguous, zero-indexed, numeric keys, it will be encoded as an array. Any other vector (object or associative array) will be encoded as an object.

    Because you are using odbc_fetch_array(), your result rows are returned as an associative array with the keys being the column names. To get the result you want you have 3 options:

    Pass the result rows through array_values():

    $json[] = array_values($row);
    

    Manually construct the individual arrays:

    $json[] = array($row['message_type'], $row['percentage']);
    

    Or probably the best option is to use odbc_fetch_row() instead, which will return indexed arrays straight away:

    while ($row = odbc_fetch_row($rs)) {
        $json[] = $row;
    }
    
    0 讨论(0)
提交回复
热议问题