Reputation: 518
I'm trying to create an array(); from the mysql results/query.
The Array OUTPUT should look exactly like this:
{"1":{"info":"Rooz","lat":51.503363,"lng":-0.127625},
"2":{"info":"Michelle","lat":51.503343,"lng":-0.127567}}
So I tried to do it this:
$sql = "SELECT id, name, lat, lng FROM positions ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
$testLocs = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$testLocs[] = $row;
}
print_r(json_encode($testLocs));
but the OUTPUT of the code above is like this:
[{"id":"1","name":"Rooz","lat":"51.5033630","lng":"-0.1276250"},{"id":"2","name":"Michelle","lat":"51.503343","lng":"-0.127567"}]
I have no idea how to achieve the output that I want in an array.
Could someone please advise on this?
any help would be appreciated.
Upvotes: 1
Views: 92
Reputation: 205
Addition to @Sean's answer: You could also use (array) $row
instead of create the array manually with every key:
$testLocs[$row["id"]] = (array) $row;
If you change your query in the future, you don't have to change this line.
Upvotes: 1
Reputation: 191729
PHP arrays are not built in a distinct way from JSON objects:
$testLocs[$row["id"]] = $row;
If you purposely want to exclude the $id
property from $row
you can remove it from the $row
array first.
$id = $row["id"];
unset($row["id"]);
$testLocs[$id] = $row;
Upvotes: 0
Reputation: 12433
Change
$testLocs[] = $row;
to
$testLocs[$row["id"]] = array("info"=>$row["name"], "lat"=>$row["lat"], "lng"=>$row["lng"]);
Upvotes: 3