Reputation: 2268
I am trying to get mysql data in to json using php and later access it in url. I am getting data in json but i need in a format. Below is my php code to get json.
header('Content-Type: application/json');
include('dbhconfig.inc.php');
$response = array();
$stmt = $dbh->prepare("SELECT * FROM venderlist");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
{
$response['results'] = $rows;
}
echo json_encode($response);
And my json data showing as bellow
{"results":[{"id":"1","vendname":"Genie Events","address":"15, Lower Ground Floor, Lajpat Nagar, Delhi - 110024, Near National Park ","contact":"(91)-11-33437065","contact_o":"(91)-11-40666522","est":"2010","website":"www.genieevents.com","email":"","zip":"110024","latitude":"1.28525","longitude":"103.775464","latlon":"1.28525,103.775464","type":"organisers"},
First of all its not showing in proper structure. And presently latlon is showing like "latlon":"1.28525,103.775464"
but i want result should be "latlon":[1.28525,103.775464]
How to add []
to my json variable name latlon.
Upvotes: 4
Views: 120
Reputation: 41885
If course, you'll need to break down that part of the data first since its a string. You'll need to set them up as an array unit with both float values inside.
After fetching them all, you'll need to make a little bit of operations.
You can use explode
on that string first with that ,
. So that becomes an array []
. But it doesn't end there, the exploded elements are still strings, so you can map out all elements with floatval
with the use of arrray_map
.
So all in all, it would look just like this:
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as &$r) { // with reference
// explode with comma, map with floatval
$r['latlon'] = array_map('floatval', explode(',', $r['latlon']));
}
echo json_encode(array('results' => $rows)); // json encode
Upvotes: 4