从mysql创建JSON结果

时间:2014-12-03 22:36:07

标签: php arrays json

如何创建这种类型的json?:

{
     "Southern", "1040",
     "South-West": "710",
     "South-East": "692",
     "Western": "638",
     "North-Western", "448",
     "Eastern": "80",
     "North-East": "9"
}

我试过这种方式,但你得不到所需:

$result = mysqli_query($db,"query"); 

       $json_response = array();

        while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
            array_push($json_response,array($row[0],$row[1]));
        }

2 个答案:

答案 0 :(得分:2)

只需从查询中获取数组并对其进行编码:

$result = mysqli_query($db,"query"); 
$json_response = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($json_response);
// OR
echo json_encode($json_response,JSON_FORCE_OBJECT);

供参考:

mysqli.query 它返回一个对象mysqli-result object,然后使用mysqli_fetch_all()返回一个由json_encode函数编码的数组。

答案 1 :(得分:1)

我假设您尝试每行有2列数据,例如?

column1        column2
"southern"     "1040"

如果是这样,只需调整构建阵列的方式:

    $result = mysqli_query($db,"query"); 

    while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
        $data[$row[0]] = $row[1];
    }
    $json_response = json_encode($data);