2014-10-27 54 views
0

嗨,所以我試圖從我的數據庫中返回所有「人」,然後創建一個「人」數據的對象,然後在每個時間的結束循環將人員添加到數組中。在while循環之外,然後編碼所述數組。如何創建一個對象數組在PHP中使用while循環

附在下面是我當前的代碼:

class person { 
    public $firstName = ""; 
    public $lastName = ""; 
} 

$people = array(); 
$result = mysqli_query($con,"SELECT * FROM People"); 

while($row = mysqli_fetch_array($result)) { 
     $firstName=$row['firstName']; 
     $lastName=$row['lastName']; 

     $e = new Person();   
     $e->firstName = $firstName; 
     $e->lastName = $lastName; 

     array_push($people, $e); 
} 

json_encode($people); 

非常感謝

+2

你有什麼特別的問題嗎? – 2014-10-27 19:03:11

+0

你的問題是什麼,朋友? – typeoneerror 2014-10-27 19:03:40

+0

我的問題是爲什麼不是上面的代碼我猜 – 2014-10-27 21:49:04

回答

1

似乎沒有在這裏的一個問題,但也許會mysqli_fetch_object在這種情況下,對你更有用。

另外,注意你的命名。你已經把你的班級稱爲「人員」,並將其實例化爲「人員」。 PHP對於案例來說非常靈活,但是這可能會導致您的程序稍後出現問題。

最後,json_encode只是編碼一個對象。如果你想顯示的結果或將其推到瀏覽器的消費,你需要回應一下:

header('Content-Type: application/json'); 
echo json_encode($people); 
0

使用「mysqli_fetch_assoc」,而不是「mysqli_fetch_array」如果你想使用一種聯想方法。

class Person 
{ 
    public $firstName = null; 
    public $lastName = null; 
} 

$people = array(); 
$result = mysqli_query($con,"SELECT * FROM `People`"); 

while($row = mysqli_fetch_assoc($result)) { 
     $e = new Person();   

     $e->firstName = $row['firstName']; 
     $e->lastName = $row['lastName']; 
} 

json_encode($people); 
相關問題