How do I fill an array inside a while loop and get new scope each iteration?

China☆狼群 提交于 2019-12-02 07:51:15

问题


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.

What's the best way to get a new scope for each iteration?

Code:

    $namesArray= array();
        while ($row=mysql_fetch_array($result))
        {
        $nameAndCode->code = $row['country_code2'];
        $nameAndCode->name = $row['country_name'];           
        array_push($namesArray,$nameAndCode);


        } 
return $namesArray;

回答1:


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;
} 

Or more concisely:

while ($row=mysql_fetch_array($result))
{
    $namesArray[] = array( 
        'code' => $row['country_code2'],
        'name' => $row['country_name']
    );
} 



回答2:


I'd go with something like:

$namesArray=array();
while($row=mysql_fetch_array($result)){
  $nameAndCode=array("code"=>$row["country_code2"],
                     "name" => $row["country_name"]);
  array_push(&$namesArray,$nameAndCode);
};

I'd also try passing $namesArray by reference, like Viktor mentioned. My code makes completely new array to push each iteration, which makes sure you dpn't overwrite stuff. Also, if you want to add stuff to an array by accessing it via its index you should use this:

// This is the right way
$someArray["foo"]="bar";
$someArray["baz"]="quux";
// This is wrong, it's only for OOP
$someArray->foo="bar";
$someArray->baz="quux";



回答3:


Try

array_push(&$namesArray,$nameAndCode);

I think array_push requires a reference or pointer.

Is there a reason you aren't using $namesArray[]? Instead of the above:

$namesArray[] = $nameAndCode;


来源:https://stackoverflow.com/questions/11727746/how-do-i-fill-an-array-inside-a-while-loop-and-get-new-scope-each-iteration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!