【发布时间】:2015-12-20 22:01:44
【问题描述】:
我有一个奇怪的问题,我找不到解决方法。 我在 PHP 中使用 JsonSerializable 接口来创建要返回的 JSON。在我正在使用的一个对象中,我有一个变量,它是一组对象。当数组仅包含一个对象但有多个对象时,它会起作用,我得到一个空数组。我不明白。这是代码:
class SessionDate implements JsonSerializable {
private $_players;
public function getPlayers() { return $this->_players; }
public function setPlayers($players) {
$this->_players = $players;
}
public function jsonSerialize(){
return [
'players' => $this->getPlayers() // This is an array of player
];
}
}
class Player implements JsonSerializable {
private $_id;
private $_name;
public function getId() { return $this->_id; }
public function setId($id) { $this->_id = $id; }
public function getName() { return $this->_name; }
public function setName($name) { $this->_name = $name; }
public function jsonSerialize(){
return [
'id' => $this->getId(),
'name' => $this->getName()
];
}
}
这就是我获得球员名单的方式:
$q = $this->_db->prepare('the query');
$q->execute();
$players = [];
while ($data = $q->fetch()) {
$sessionPlayer = constructPlayer($data);
$players[] = $sessionPlayer;
}
return $players;
我做错了什么?为什么只有一个玩家而不是更多玩家时它会起作用??
谢谢。
** 编辑 **
我用 $.ajax 调用 php 操作,似乎当有多个玩家时,$.ajax 响应会出错。所以可能是因为 JSON 格式不正确...
【问题讨论】:
-
constructPlayer是什么? -
只是给对象播放器的一系列设置数据。这是有效的,因为只有一个我得到所有数据......
标签: php arrays json object nested