1

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.

3 Answers 3

3

Change

$testLocs[] = $row;

to

$testLocs[$row["id"]] = array("info"=>$row["name"], "lat"=>$row["lat"], "lng"=>$row["lng"]);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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;

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.