[英]PHP json_encode returns empty string with array of objects
我在php中有以下数组(使用var_dump)。
array(135) {
[0]=>
object(Book)#138 (2) {
["id"]=>
string(36) "93ec4cd6-49a3-4dc6-94f1-00295cc9cdaf"
["title"]=>
string(33) "title 1"
}
[1]=>
object(Book)#139 (2) {
["id"]=>
string(36) "830fe4b8-927d-4a4c-9398-033358d64551"
["title"]=>
string(12) "title 2"
}
[2]=>
object(Book)#140 (2) {
["id"]=>
string(36) "3ed31443-666c-4d20-81c2-067e42047007"
["title"]=>
string(8) "title 3"
}
我想回显一个json字符串,以便可以按角度读取它。
我使用echo json_encode($ books);
但是我得到一个空字符串。
关于如何将此数组转换为json的任何想法?
Syscall和Trincot发表第一个评论后的其他信息:
书类
class Book implements JsonSerializable {
public $id;
public $title;
public function __construct($id = '', $title = '') {
$this->id = $id;
$this->title = $title;
}
public function jsonSerialize() {
return get_object_vars($this);
}
}
书库
require_once 'DBHelper.php';
require_once 'Book.php';
class BookRepository {
public static function getReeksen() {
$conn = new PDO("mysql:host=" . DBHelper::$DB_SERVERNAME .";dbname=" . DBHelper::$DB_DATABASENAME, DBHelper::$DB_USERNAME, DBHelper::$DB_PASSWORD);
$sql = "SELECT id, naam FROM BC_Book";
$books = array();
$statement = $conn->prepare($sql);
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_CLASS);
foreach ($result as $db_book) {
$book = new Book($db_book->id, $db_book->title);
array_push($books, $book);
}
return $books;
}
}
这是因为var_dump()
显示对象的值,包括对象的私有字段,而json_encode()
则不显示。
您需要实现JsonSerializable
:
class Book implements JsonSerializable {
private $id ;
private $title ;
public function __construct($id,$title) {
$this->id = $id;
$this->title = $title;
}
public function jsonSerialize()
{
return get_object_vars($this);
}
}
$arr = [
new Book("93ec4cd6-49a3-4dc6-94f1-00295cc9cdaf","title 1"),
new Book("830fe4b8-927d-4a4c-9398-033358d64551","title 2"),
];
var_dump(json_encode($arr));
输出:
"[{"id":"93ec4cd6-49a3-4dc6-94f1-00295cc9cdaf","title":"title 1"},{"id":"830fe4b8-927d-4a4c-9398-033358d64551","title":"title 2"}]"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.