简体   繁体   中英

php json encode format

I have simple code

$result = mysql_query("select * from wizard"); 

    $rows = array();
    while($r = mysql_fetch_array($result))
    {
        $rows[] = $r;       
    }
    echo json_encode($rows);

My result

[{"0":"1","id":"1","1":"121","fid":"121","2":"4","meth_id":"4","3":"A",

instead of

[{"id":"1","fid":"121","meth_id":"4",

What is the problem of such kind of format and how can I fix it.

Thank you

You need to include the second result_type parameter with value MYSQL_ASSOC when calling mysql_fetch_array.

while($r = mysql_fetch_array($result, MYSQL_ASSOC))

Otherwise, MYSQL_BOTH default value is used, and you get an array with both associative and number indices http://php.net/manual/en/function.mysql-fetch-array.php , thus your duplicated values in the result array.

And also you are discouraged to use deprecated mysql_* functions, and using instead MySQLi or PDO , but that's up to you.

您可能需要检查 json_encode 中得到的结果是否是一个数组mysql_fetch_assoc尝试使用mysql_fetch_assoc而不是mysql_fetch_array

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