2011-06-03 59 views
0

我有開始像這樣的幾行代碼獲取數據時覆蓋:第一個數組元素得到第二從數據庫使用PHP

$trailheads = array(); 
// Then a db call with a query. Then loop through the results. 

// This gives a diff value every time, so here we are still ok 
$trailhead->trailhead_name = $row['trailhead_name']; 

// Before the look iteration ends, I do something like this: 
array_push ($trailheads , $trailhead); 
// But I could have done this with the same result: 
$trailheads[] = $trailhead; 

而且一旦我退出循環,我做的print_r,它顯示查詢返回的兩行中的第二行覆蓋第一行。

這裏是循環的完整版本:

while($row = mysql_fetch_assoc($trailhead_result)) 
    { 
     $trailhead->trailhead_name = $row['trailhead_name']; 


     $trailhead->park_id = $row['park_id']; 
     $trailhead->trailhead_id = $row['trailhead_id']; 
     $trailhead->trailhead_description = $row['trailhead_description']; 
     $trailhead->parking = $row['parking']; 
     $trailhead->lat = $row['lat']; 
     $trailhead->lng = $row['lng']; 
     $trailhead->is_free = $row['is_free']; 
     $trailhead->parking_spots = $row['parking_spots']; 
     $trailhead->cost_details = $row['cost_details']; 

     $trailheads[] = $trailhead; 
    } 
+1

顯示完整的代碼。 – 2011-06-03 22:29:57

+0

是否每次都重新初始化$ trailhead的值?它可能有助於發佈循環的更完整版本 – 2011-06-03 22:29:58

+0

在循環期間嘗試執行'print_r()',以便您可以清楚地看到數組被覆蓋的位置和原因。 – drudge 2011-06-03 22:30:59

回答

3

如果這是你的全循環,再一個問題是,你沒有初始化$trailhead循環。這樣做:

while($row = mysql_fetch_assoc($trailhead_result)) 
{ 
    $trailhead = new trailhead(); 
    $trailhead->trailhead_name = $row['trailhead_name']; 
    $trailhead->park_id = $row['park_id']; 
    $trailhead->trailhead_id = $row['trailhead_id']; 
    $trailhead->trailhead_description = $row['trailhead_description']; 
    $trailhead->parking = $row['parking']; 
    $trailhead->lat = $row['lat']; 
    $trailhead->lng = $row['lng']; 
    $trailhead->is_free = $row['is_free']; 
    $trailhead->parking_spots = $row['parking_spots']; 
    $trailhead->cost_details = $row['cost_details']; 

    $trailheads[] = $trailhead; 
} 

我必須假定對象$trailhead是一個名爲trailhead類。如果不是,請使用任何類別代替new trailhead()

+0

@AJ你的建議修復了它 - 謝謝! – GeekedOut 2011-06-03 22:41:17

+0

沒問題...祝你好運。 – 2011-06-03 22:46:43

相關問題