在PHP foreach语句中没有将值添加到数组中

时间:2015-11-10 21:48:27

标签: php arrays

我遇到一个foreach语句的问题,我尝试在数组中添加一个额外的值,它似乎工作正常,但现在突然间它不再有效。

当我在添加到$application['agency']的值的for循环中执行var_dump时,它显示了值,但是一旦我离开for语句并运行var_dump($applications);它就不再具有值它

我确信我错过了一些小但却看不到的东西。有人可以帮忙吗?

代码:

foreach($applications as $application) {
        if (is_array($application)) {
            $agenciessarray=db_select("select agency_name from `agencies` where `agency_id`=".db_quote($application['agency_id']));
            //var_dump($agenciessarray);
            //echo '<br/>';
            $application['agency'] = $agenciessarray[0]['agency_name'];
            //var_dump($application['agency']);
            //echo '<br/>';
        }
    }

var_dump($applications);

结果:

array(3) { 
    [0]=> array(7) { 
        ["application_id"] => string(4) "1002" 
        ["first_names"] => string(6) "asdads" 
        ["surname"] => string(6) "asdasd" 
        ["id_number"] => string(6) "123123" 
        ["cell_number"] => string(4) "sadf" 
        ["email_address"] => string(0) "" 
        ["agency_id"] => string(1) "2" 
    } 
    [1]=> array(7) { 
        ["application_id"] => string(4) "1003" 
        ["first_names"] => string(6) "asdads" 
        ["surname"] => string(6) "asdasd" 
        ["id_number"] => string(6) "123123" 
        ["cell_number"] => string(4) "sadf" 
        ["email_address"] => string(0) "" 
        ["agency_id"] => string(1) "2" 
    } 
    [2]=> array(7) { 
        ["application_id"] => string(4) "1004" 
        ["first_names"] => string(6) "asdads" 
        ["surname"] => string(6) "asdasd" 
        ["id_number"] => string(6) "123123" 
        ["cell_number"] => string(4) "sadf" 
        ["email_address"] => string(0) "" 
        ["agency_id"] => string(1) "2" 
    } 
}

1 个答案:

答案 0 :(得分:1)

问题是您修改了$applications数组元素的本地副本。它仅存在于循环内部。您需要访问数组中的实际变量。

其中一个解决方案是将数组键$k包含在循环中,然后通过它引用数组元素。

foreach($applications as $k => $application) {
            // .......
            $applications[$k]['agency'] = $agenciessarray[0]['agency_name'];
            // .......
        }
    }

PHP documentation for foreach还建议通过引用将变量传递给循环来实现此目的。例如:

foreach($applications as &$application) {
            // .......
            $application['agency'] = $agenciessarray[0]['agency_name'];
            // .......
        }
    }