我在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字符串,所以我可以用angular读取它。
我使用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);
}
}
BookRepository
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;
}
}
答案 0 :(得分:4)
这是因为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"}]"