I have this class with three variables, one of them being an array. I have written a method that I'll use inside json_encode().
public function getJSONString(){
return [
'id' => $this->id,
'name' => $this->name,
'books' => $this->books
];
}
books is an array of Book objects. Each Book object also has the same exact method but then with its own variables.
public function getJSONString(){
return [
'id' => $this->id,
'title' => $this->title
];
}
When I call print(json_encode($author->getJSONString())) I recieve this:
{"id":"1","name":"name1","books":[{},{}]}
Any idea why books remains empty? Thanks in advance!
2 Answers 2
You will need to use the Books' getJSONString() methods as well. This will make the the books property equal to an array of JSON-encode-able objects.
In the author's getJSONString() method:
public function getJSONString(){
return [
'id' => $this->id,
'name' => $this->name,
'books' => array_map(function($book) { return $book->getJSONString(); }, $this->books)
];
}
I am not fluent in PHP, but you can get the idea from this. It maps a function to get the getJSONString() over the books array.
7 Comments
$book->getJSONString(). Tell me if it works now.JsonSerializer is the cleaner way to go. See my answer.You should definitely use JsonSerializable interface.
class Book implements JsonSerializable
{
public function jsonSerialize() {
return [
'id' => $this->id,
'title' => $this->title
];
}
}
When you call json_encode for an object of this class or anything contains that, php will call your jsonSerialize method. Similar to what you are trying to do, but this is the language specific and right way to do it. Other languages like C# has similar interfaces too.
$this->booksis empty. Check if it's emptyvar_dump($this->books)and check the code that sets it's value may be it is executing after you calledgetJSONString()print_r()your variable and see.