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

前端 未结 3 1422
死守一世寂寞
死守一世寂寞 2021-01-25 06:57

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 c

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-25 07:13

    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']
        );
    } 
    

提交回复
热议问题