如何在while循环内填充数组,并在每次迭代时获取新作用域? [英] How do I fill an array inside a while loop and get new scope each iteration?

查看:54
本文介绍了如何在while循环内填充数组,并在每次迭代时获取新作用域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是我只从表中得到最后一个值.我认为是因为我在构建数组时将其值引用到同一个对象,并且它一直在变化.我知道while循环不会为 IS 问题的每次迭代创建新的作用域.

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循环内填充数组,并在每次迭代时获取新作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆