1

i retrieve and print data from MySQL database in json method:

$ret = array();

$fileName = Access::FetchDB("SELECT name FROM tags");
    $ret[]= $fileName;
echo json_encode($ret);

Now output is:

[[{"name":"test1"},{"name":"test2"},{"name":"test3"}]]

But i need to This output:

["test1","test2","test3"]

How do i print this?

1
  • Just loop over $fileName and put the values into $ret. Commented Jan 24, 2014 at 19:19

2 Answers 2

5
[[{"name":"test1"},{"name":"test2"},{"name":"test3"}]]

is like having this

array(array(array('name' => 'test1'), array('name' => 'test2'), array('name' => 'test3')));

First, do not do this:

$ret[]= $fileName;

And keep only $fileName which should be something like this:

array(array('name' => 'test1'), array('name' => 'test2'), array('name' => 'test3'));

The better would even be to have array('test1', 'test2', 'test3') and encode it without array_values(). You could do it in php side:

$ret = array();
$fileName = Access::FetchDB("SELECT name FROM tags");

foreach($fileName as $key => $value)
   $ret[] = $value['name'];

echo json_encode($ret);
Sign up to request clarification or add additional context in comments.

1 Comment

i tested but not worked for me! i see [[{"name":"test1"},{"name":"test2"},{"name":"test3"}]] output.
1

Try this solution:

$ret = array();

$fileNames = Access::FetchDB("SELECT name FROM tags");
$ret = array_values($fileNames);
echo json_encode($ret);

2 Comments

Unfortunately, this won't work. I answered something similar at first, see my answer to understand why
I didn't notice the array in array, only the key value pairs. Sorry my fault.

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.