I'm looking for an efficient way to use json_encode for an array of objects. The issue I have is that my objects all have private properties (use getters and setters) and json_encode won't pull those in. So I created a jsonSerialize function for an object with returns the private variables but I don't know how to execute the function for each object in the array efficiently. I could use a loop to execute the jsonSerialize function for each object but that I'm afraid that may be too slow.
class car
{
private $make, $model;
public function jsonSerialize()
{
return get_object_vars($this);
}
}
Controller function to return list of cars in json format
$cars = $db->getAllCars(); //returns an array of objects using fetchall
return json_encode($cars);
You can't use json_encode for objects, it's written in the manual (http://php.net/manual/en/function.json-encode.php)
First you need to implement in your object the JsonSerializable interface to achieve what you're looking for (http://php.net/manual/en/jsonserializable.jsonserialize.php).
In your case you're missing the interface declaration. Try this
class car implements JsonSerializable
{
private $make, $model;
public function jsonSerialize()
{
return get_object_vars($this);
}
}
You can use the JsonSerializable type like this:
class Car implements JsonSerializable
{
private $make, $model;
public function jsonSerialize() {
return array($this->make, $this->model);
}
}
var $car = new Car();
echo json_encode($car, JSON_PRETTY_PRINT);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With