How to send an array of objects in JSON format from PHP
When iterating over a database result set, it is easy to overwrite your data structure if you are not careful. In the scenario provided, the code fragment initializes $list as an associative array inside a while loop that fetches rows. Because this assignment happens on every iteration without accumulation, the final output reflects only the last row fetched from the SQL query. The front-end receives a single object rather than a collection, resulting in data like {"id": 12, "name": "Manisha"} instead of an array containing all records.
To resolve this, you must initialize a container variable outside the loop and push each new record into it. This approach ensures that every row processed by $stmt->fetch() is preserved in memory until the query completes. Once the loop finishes, you can convert the accumulated collection into a JSON string using json_encode().
Here is how to structure the code correctly:
$results = []; // Initialize an empty array outside the loop
while ($stmt->fetch()) {
$results[] = [
'id' => $fid,
'name' => $fname
];
}
$stmt->free_result();
$stmt->close();
echo json_encode($results);
In this implementation, $results acts as a bucket. Every time the while loop executes, a new associative array is created for the current row and appended to $results. When json_encode() processes $results, it automatically wraps the collection in square brackets, producing the desired format: [{"id":"1","name":"Kumari"}, {"id":"2","name":"KM"}, {"id":"3","name":"Manisha"}].
There are specific behaviors of json_encode() that affect the output structure. By default, when encoding an array of arrays or objects, PHP includes curly braces {} for each object and square brackets [] for the outer array. However, if you attempt to encode a single associative array without wrapping it in an outer array, it will not be treated as a list. This is why the initial code failed; it was essentially trying to encode the last element of a growing array as the final result, effectively discarding previous iterations.
Another consideration involves the JSON_UNESCAPED_UNICODE flag or similar options depending on your version of PHP and specific character set requirements. If your names contain special characters, ensure that the JSON encoding respects your application's encoding standards to prevent double-encoding issues. While modern PHP versions handle UTF-8 robustly by default, being explicit about encoding can save debugging time in production environments.
If you are working within a larger Laravel ecosystem, you might prefer using Laravel Collections or Eloquent relationships to handle this logic. For instance, if $stmt represents an Eloquent query result, you could map the results directly into a collection before encoding:
$results = collect($stmt->fetchAll(PDO::FETCH_ASSOC))
->map(function ($row) use ($fid, $fname) {
return ['id' => $fid, 'name' => $fname];
});
echo json_encode($results);
This pattern leverages the collection methods available in Laravel to transform data before serialization. It also allows for easy chaining of methods like map, filter, or pluck if you need to manipulate the dataset further before sending it to the front-end.
Ultimately, the distinction lies in whether your target variable is a single associative array or an indexed array containing multiple objects. The fix requires ensuring that your data accumulator is treated as a list throughout the entire execution of your script, not just at the point of output.