You start by defining an array.
You then generate some JSON manually.
You then convert the array to JSON and output it.
Replace all the echo statements in and at the edge of your while loop with code to generate an associative array containing the data, and then insert it into $json.