1

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

1
  • 1
    Change mysql_* to mysqli or PDO? Commented Feb 10, 2013 at 9:33

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you it works now. I seen a tutorial how to do it but then I had arrays inside arrays.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.