Reputation: 1457
I'm trying to create a associative array using PHP. I'm using a ajax script that calls a json file.
I have tested the script using the following PHP code:
$testLocs = array(
'loc5' => array( 'info' => 'Some random info', 'lat' => 0, 'lng' => 60 ),
'loc6' => array( 'info' => 'Some random info', 'lat' => 0, 'lng' => 40.345 )
);
echo json_encode($testLocs);
which echos:
{"loc1":{"info":"Some random info","lat":0,"lng":60},"loc1":{"info":"Some random info","lat":0,"lng":40.345}}
The ajax code will work correctly. Now I'm trying to write a PHP script that will get the info from the database. My PHP code is below
$query = "Select * from table";
$result = mysql_query($query);
$json_data = array();
while ($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
$lat = $row['lat'];
$lon = $row['lon'];
$page = $row['page'];
array_push($json_data, array('info' => 'Some random info', 'lat' => $lat, 'lng' => $lon));
}
echo json_encode($json_data);
which echos:
{"info":"Some random info","lat":"-31.9522","lng":"115.8614"},{"info":"Some random info","lat":"40.7842","lng":"-73.8422"}
I cannot figure out how to put 'loc' =>
in front of each array. The ajax is using The locNUM as a unique ID.
Thank you
Upvotes: 1
Views: 1961
Reputation: 15106
If $row['id']
is the unique ID for locNUM:
$json_data["loc".$id] = array('info' => 'Some random info', 'lat' => $lat, 'lng' => $lon)
array_push()
is the same as $array[] = $var;
, which gives you an incremented numeric key.
Upvotes: 0
Reputation: 3345
try
$json_data = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
$lat = $row['lat'];
$lon = $row['lon'];
$page = $row['page'];
$json_data["loc" . ($i++)] = array('info' => 'Some random info', 'lat' => $lat, 'lng' => $lon);
}
instead of array_push
.
array_push
is meant as a pure array function, not as a hash manipulating function.
Upvotes: 1