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.
    – gen_Eric
    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);
1
  • i tested but not worked for me! i see [[{"name":"test1"},{"name":"test2"},{"name":"test3"}]] output.
    – Pink Code
    Jan 24, 2014 at 19:25
1

Try this solution:

$ret = array();

$fileNames = Access::FetchDB("SELECT name FROM tags");
$ret = array_values($fileNames);
echo json_encode($ret);
2
  • Unfortunately, this won't work. I answered something similar at first, see my answer to understand why Jan 24, 2014 at 20:34
  • I didn't notice the array in array, only the key value pairs. Sorry my fault.
    – bvarga
    Jan 24, 2014 at 21:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.