1

I am using this code to build an array and encode it to JSON.

   while($row = mysqli_fetch_array($sql)) {

   $results[] = array(
      'wdatatype' => $row['wdatatype'],
      'wdb' => $row['wdb'],
      'wbyte' => $row['wbyte'],
      'wbit' => $row['wbit'],
      'bitval' => $row['bitval'],     
   );

   }
       $json = json_encode($results);
       echo $json;

The output is this

     [{"wdatatype":"DB","wdb":"100","wbyte":"0","wbit":"0","bitval":"1"}] 

But for my jQuery script I need the output to be

     {"wdatatype":"DB","wdb":"100","wbyte":"0","wbit":"0","bitval":"1"}

How do I accomplish this?

Thanks!

1
  • 9
    What should output look like if you have more than one row? Commented May 7, 2014 at 15:07

1 Answer 1

4

You're problem seems to stem from the fact that you're creating a multi-dimensional array. You're pushing an array as an element of the existing $results array. For you're desired output, $results should be an associative array, not an array of associative arrays.

Provided there is only one row in your result set, try this instead:

// Remove the while loop if you're only returning a single row
// such as with a LIMIT = 1 clause in your SQL statement.
$row = mysqli_fetch_array($sql);

// Push the single row as an array into $result
$results = array(
    'wdatatype' => $row['wdatatype'],
    'wdb' => $row['wdb'],
    'wbyte' => $row['wbyte'],
    'wbit' => $row['wbit'],
    'bitval' => $row['bitval'],     
 );

// Now echo the json_encode
echo json_encode($results);

When converted using json_encode, the above will turn into a single object like so:

{"wdatatype":"DB","wdb":"100","wbyte":"0","wbit":"0","bitval":"1"}

rather than an array of objects.

Note: As @PankajGarg and @AmalMurali pointed out this should be used if you're only returning a single row. Failing to remove the while loop and returning a result set of more than one row will yield you a return of the last row only.

For a result set containing multiple rows, your current structure will work perfectly.

Alternatively as @Nilpo pointed out, you can simplify the above process by using mysqli_fetch_assoc() to return an associative array for you.

$row = mysqli_fetch_assoc($sql);

// Now echo the json_encode
echo json_encode($row);
Sign up to request clarification or add additional context in comments.

14 Comments

What if there is more than one row ?
Wow! it was that easy? Thanks a lot!
Since all of your columns names are the same, why not just use mysqli_fetch_assoc() and skip all of this?
@Nilpo Thanks for the feedback/edit. I've added your name for credit.
There is one problem with $row = mysqli_fetch_assoc($sql); If I use this it will return all columns in my table, however there are 2 columns I want to exclude from the object.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.