Sebastiano
Sebastiano

Reputation: 113

Creating a JSON result from mysql

How to create this type of json?:

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

I tried this way but you do not get that you need:

$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]));
        }

Upvotes: 2

Views: 81

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78984

I assume from your attempt that each row has 2 columns with the data for example?

column1        column2
"southern"     "1040"

If so, just tweak how you build the array:

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

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

Upvotes: 1

SaidbakR
SaidbakR

Reputation: 13534

Simply get an array from your query and encode it:

$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);

For reference:

mysqli.query It returns an object, mysqli-result object, then use mysqli_fetch_all() that returns an array which is encoded by json_encode function.

Upvotes: 2

Related Questions