我有開始像這樣的幾行代碼獲取數據時覆蓋:第一個數組元素得到第二從數據庫使用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;
}
顯示完整的代碼。 – 2011-06-03 22:29:57
是否每次都重新初始化$ trailhead的值?它可能有助於發佈循環的更完整版本 – 2011-06-03 22:29:58
在循環期間嘗試執行'print_r()',以便您可以清楚地看到數組被覆蓋的位置和原因。 – drudge 2011-06-03 22:30:59