Possible Duplicate:
How to modify an array's values by a foreach loop?
为什么这不起作用?
$user_list_array = array(
1 => array( "first_name" => "Jim" ),
2 => array( "first_name" => "Bob" )
)
foreach ($user_list_array as $item ) {
echo $item["first_name"];
$item["last_name"] = "test";
}
var_dump($user_list_array );
我可以找回“first_name”,但无法添加“last_name”;
最佳答案
您正在修改 $item,它是 $user_list_array 相关条目的副本
两者之一: (修改原数组)
foreach ($user_list_array as $key => $item ) {
echo $item["first_name"];
$user_list_array[$key]["last_name"] = "test";
}
或: (引用)
foreach ($user_list_array as &$item ) {
echo $item["first_name"];
$item["last_name"] = "test";
}
unset($item);
关于PHP:如何从 foreach 循环内部修改数组(通过引用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12652877/