Bavilo
Bavilo

Reputation: 409

Wrong output json_encode PHP

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!

Upvotes: 1

Views: 1192

Answers (1)

War10ck
War10ck

Reputation: 12508

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);

Upvotes: 4

Related Questions