我希望在从数据库中获取数据之后,使用相同的键和不同的值创建对象数组。在json_encode()之后的可变格式如下所示:
[
{'username':'admin' ,'name':'Sean' ,'lastname':'Paul'},
{'username':'admin2','name':'Nikola','lastname':'Tesla'},
{'username':'admin3','name':'Nick','lastname':'Nickolas'}
]
我的代码如下所示:
private function getUsernames(){
$sql = "SELECT username,name,lastname FROM users";
$connect = new Database($username="",$password="");
$connect->connect();
$result = $connect->db->query($sql);
$adminObject = new stdClass();
while($row = $result -> fetch(PDO::FETCH_ASSOC)){
$adminObject -> username = $row['username'];
$adminObject -> name = $row['name'];
$adminObject -> lastname = $row['lastname'];
$this->usernames = $adminObject;
}
此代码只输出一个对象,最后一个在DB中。有没有任何解决方案,不使用Doctrine,Eloquent或任何其他ORM?
答案 0 :(得分:3)
您需要的输出是一个对象数组,这可以使用单个pdo方法fetchAll
来实现,并传入正确的标记PDO::FETCH_OBJ
:
private function getUsernames()
{
$sql = "SELECT username,name,lastname FROM users";
$connect = new Database($username = "", $password = "");
$connect->connect();
$result = $connect->db->query($sql);
$this->usernames = $result->fetchAll(PDO::FETCH_OBJ));
//for your desired json: echo json_encode($this->usernames);
}