使用PHP从数据库获取数据时,第一个数组元素被第二个数组元素覆盖


First array element getting overwritten by the second when getting data from db using 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;
    }

如果这是您的完整循环,那么一个问题是您没有在循环内初始化$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()