0

I'm facing a problem with reading an associative array from an SQL query on my PostgreSQL database.

So here's my database:

ID | NAME | ....
1  | CARS | 
2  | BIKES| 
3  | TRAINS |

Now I have a PHP script that I want to grab some data from that query and encode it into JSON for a mobile device.

Here is the script:

    $res = pg_query("SELECT * FROM projects");

/* FETCHES THE RESULT OF THE SQL QUERY WHICH GETS THE NAME OF EACH PROJECT */
while($row = pg_fetch_assoc($res))
{
    $output[]=$row['name'];
    print (json_encode($output));
}  /* CONVERTED ON MOBILE PLATFORM */

pg_close(); 

Now the result I'm getting is shown copy and pasted from the output of the file (below):

["Cars"]["Cars","Bikes"]["Cars","Bikes","Trains"]

I can clearly see that my algorithm is indexing the records is a sort of 1, 1,2, 1,2,3 kind of way. Has anyone got any advice on how to solve this and to get this output:

["Cars"]["Bikes"]["Trains"]
2
  • What happens if you change $output[] to $output? Commented Oct 21, 2013 at 11:59
  • @mavroprovato it produces "Cars", "Bikes", "Trains" without the []! I believe that is what I want but are they separate values or an individual value? I need them to be separate as I'm populating a spinner on an android device! Commented Oct 21, 2013 at 12:02

1 Answer 1

1

You should just print the array at the end, after it was fully populated:

$res = pg_query("SELECT * FROM projects");

/* FETCHES THE RESULT OF THE SQL QUERY WHICH GETS THE NAME OF EACH PROJECT */
while($row = pg_fetch_assoc($res))
{
    $output[]=$row['name'];
}  /* CONVERTED ON MOBILE PLATFORM */

print (json_encode($output));

pg_close();

Alternatively, you could reinitialize the $output array if you need to output the individually. Depends on what you want to achieve:

$res = pg_query("SELECT * FROM projects");

/* FETCHES THE RESULT OF THE SQL QUERY WHICH GETS THE NAME OF EACH PROJECT */
while($row = pg_fetch_assoc($res))
{
    $output = array();
    $output[]=$row['name'];
    print (json_encode($output));
}  /* CONVERTED ON MOBILE PLATFORM */

pg_close(); 
2
  • second solution suggested gave the result ["Cars", "Bikes", "Trains"] which is three separate values in an array. Cheers :) Commented Oct 21, 2013 at 13:05
  • sure, good luck. i'll edit the answer to highlight the desired solution. Commented Oct 21, 2013 at 13:07

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.