arti arti -4 years ago 60
JSON Question

JSON giving weird output in php

I'm learning php as well as JSON and can't figure out why I have following output:

JSON RESULT:

{
"Results": [
{
"user_id": "1"
},
{
"email": "user@example.com"
},
{
"first_name": "User"
},
{
"last_name": "One"
},
{
"password": "pass1"
},
{
"creation_date": null
},
{
"profile_type": "0"
},
{
"user_id": "2"
},
{
"email": "user2@example.com"
},
{
"first_name": "User"
},
{
"last_name": "Two"
},
{
"password": "pass2"
},
{
"creation_date": null
},
{
"profile_type": "0"
}
]
}


PHP:

<?php
require_once 'config/db.php';
$sql = new db();
$conn = $sql->connect();

$query = isset($_GET['query']) ? mysql_real_escape_string($_GET['query']) : "";


if(!empty($query))
{
$qur = mysql_query($query);
$result = array();

while($r = mysql_fetch_assoc($qur))
{
extract($r);
foreach($r as $key => $value)
{
$result[] = array($key => $value);
}
$json = array("Results" => $result);
}
}

@mysql_close($conn);

/* Output header */
header('Content-type: application/json');
echo json_encode($json, JSON_PRETTY_PRINT);
?>


My question is, why does it split each value into new record, I want each MySQL record to be one JSON record.

Answer Source

Just assign your row to $result:

while($r = mysql_fetch_assoc($qur))
{
    $result[] = $r;
}
$json = array("Results" => $result);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download