3

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?

1
  • 3
    Just replace this line $r[] = array($data['username']); with this one $r[] = $data['username']; Commented Aug 23, 2019 at 1:33

3 Answers 3

1

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

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

Comments

0

You are assigning an array to another array. see this attached change:

<?php
require_once("../con.php");

$list = mysqli_query($con,"SELECT * FROM user WHERE reff='admin'");
$r = [];
while($data = mysqli_fetch_array($list)) {
    $r[] = $data['username'];
}
echo json_encode($r, JSON_PRETTY_PRINT);
?>

Comments

0

1.

Replace $r[] = array($data['username']);

To $r[] = $data['username'];

2.

"SELECT username FROM user WHERE reff='admin'" // * -> username 
// in while
$r[] = $data[0];
or
$r[] = current($data);

3.format in sql

SELECT CONCAT('[',GROUP_CONCAT('"',username,'"'),']') FROM user WHERE reff='admin'

see. https://dba.stackexchange.com/questions/192208/mysql-return-json-from-a-standard-sql-query

  1. if your mysql v5.7.22+

use function JSON_ARRAY、JSON_OBJECT、JSON_QUOTE in sql https://dev.mysql.com/doc/refman/5.7/en/json-creation-functions.html

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.