本文介紹了如何在 while 循環中填充數組并在每次迭代中獲得新范圍?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
問題是我只得到來自表的最后一個值.我認為這是因為我在將數組的值引用到同一個對象的同時構建數組,并且它一直在變化.我知道 while 循環不會為每次迭代創建一個新的范圍,是問題.
The problem is that I get only the last value comming from the Table. I think its because I am building the array while referencing its values to the same object, and it keeps changing. I know while loop doesnt create a new scope for each iteration which IS the problem.
為每次迭代獲得新范圍的最佳方法是什么?
代碼:
$namesArray= array();
while ($row=mysql_fetch_array($result))
{
$nameAndCode->code = $row['country_code2'];
$nameAndCode->name = $row['country_name'];
array_push($namesArray,$nameAndCode);
}
return $namesArray;
推薦答案
您需要在每次迭代時創建一個新對象:
You need to create a new object on each iteration:
while ($row=mysql_fetch_array($result))
{
$nameAndCode = new stdClass;
$nameAndCode->code = $row['country_code2'];
$nameAndCode->name = $row['country_name'];
$namesArray[] = $nameAndCode;
}
否則,您將一遍又一遍地引用同一個對象,而只會覆蓋其值.
Otherwise you're referencing the same object over and over, and just overwriting its values.
如果你不需要對象,你也可以用數組來做到這一點:
You also can do this with arrays if you don't require objects:
while ($row=mysql_fetch_array($result))
{
$nameAndCode = array();
$nameAndCode['code'] = $row['country_code2'];
$nameAndCode['name'] = $row['country_name'];
$namesArray[] = $nameAndCode;
}
或者更簡潔:
while ($row=mysql_fetch_array($result))
{
$namesArray[] = array(
'code' => $row['country_code2'],
'name' => $row['country_name']
);
}
這篇關于如何在 while 循環中填充數組并在每次迭代中獲得新范圍?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!