garcon1986 0 Light Poster

Hello everyone,

I have a problem when i use json and array. And i need your help.

Here is my code:

while($row = mysql_fetch_assoc($result)){
			echo json_encode($row);
		}

The result is:

{"id":"1","title":"event1","start":"2009-11-10 14:18:15","end":"2009-11-03 14:38:22","allDay":"false","url":null}{"id":"2","title":"event2","start":"2009-11-09 15:41:20","end":"2009-11-10 16:41:25","allDay":"false","url":null}

But i want the result is like this:

[{"id":"1","title":"event1","start":"2009-11-10 14:18:15","end":"2009-11-03 14:38:22","allDay":"false","url":null},{"id":"2","title":"event2","start":"2009-11-09 15:41:20","end":"2009-11-10 16:41:25","allDay":"false","url":null}]

How can i accomplish this? Thanks

Dani AI

Generated

For : encode the whole result set, not each row. Collect rows into a PHP array, optionally normalize fields (for example convert the "allDay" string to a boolean), then call json_encode once. Also send the JSON content-type header and check for encoding errors if results look wrong.

Example using mysqli (push each row, convert allDay to boolean, then encode once):

$rows = array();

while ($row = mysqli_fetch_assoc($result)) {
    if (isset($row['allDay'])) {
        $row['allDay'] = filter_var($row['allDay'], FILTER_VALIDATE_BOOLEAN);
    }
    $rows[] = $row;
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode($rows);

Notes and troubleshooting:

  • If using PDO, fetchAll(PDO::FETCH_ASSOC) returns the same array in one call.
  • filter_var(..., FILTER_VALIDATE_BOOLEAN) converts "true"/"false"/"1"/"0" to real booleans before encoding.
  • If json_encode returns false or output looks odd, diagnose with json_last_error_msg(); see the PHP docs: json_encode and json_last_error_msg.
  • Avoid deprecated mysql_* functions; prefer mysqli or PDO for security and future compatibility (see mysqli_result::fetch_assoc and PDOStatement::fetchAll).
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.