問題描述
問題是我只得到來自表的最后一個(gè)值.我認(rèn)為這是因?yàn)槲以趯?shù)組的值引用到同一個(gè)對(duì)象的同時(shí)構(gòu)建數(shù)組,并且它一直在變化.我知道 while 循環(huán)不會(huì)為每次迭代創(chuàng)建一個(gè)新的范圍,是問題.
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;
推薦答案
您需要在每次迭代時(shí)創(chuàng)建一個(gè)新對(duì)象:
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;
}
否則,您將一遍又一遍地引用同一個(gè)對(duì)象,而只會(huì)覆蓋其值.
Otherwise you're referencing the same object over and over, and just overwriting its values.
如果你不需要對(duì)象,你也可以用數(shù)組來做到這一點(diǎn):
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;
}
或者更簡(jiǎn)潔:
while ($row=mysql_fetch_array($result))
{
$namesArray[] = array(
'code' => $row['country_code2'],
'name' => $row['country_name']
);
}
這篇關(guān)于如何在 while 循環(huán)中填充數(shù)組并在每次迭代中獲得新范圍?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!