I have a mysql database, I want to change it to json format with results like the one below
["aaa","bbb","ccc"]
but when I made the code using PHP as below
<?php
require_once("../con.php");
$list = mysqli_query($con,"SELECT * FROM user WHERE reff='admin'");
$r = array();
while($data = mysqli_fetch_array($list)) {
$r[] = array($data['username']);
}
echo json_encode($r, JSON_PRETTY_PRINT);
?>
the results are different from what I want, the following results
[ [ "aaa" ], [ "bbb" ], [ "ccc" ] ]
is there any suggestion how to fix it?
The best way to do is $r[] = $data['username']; instead of $r[] = array($data['username']); because with this line $r[] = array($data['username']); you are trying to push username as an array not a username string value every time on your $r that's why it creates extra brackets [] surrounding your username value.
but if you don't want to change your existing code then you can use this to get result as expected with this extra line of code $r = array_merge(...$r), here ... known as the splat operator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With