这是代码
$tasks = $project->getTasks();
foreach ($tasks as $key => $task) {
$task['position'] = $space->getPosition();
$task['symbol'] = $space->getSymbol();
}
Run Code Online (Sandbox Code Playgroud)
逻辑上'position'和'symbol'应该添加在数组'task'中.它们实际上是添加的,但仅限于循环内部.它们在循环外消失.为什么?
by value除非另有说明,否则PHP foreach循环操作(在数据的副本上).有两种可能的解决方案
foreach ($tasks as $key => $task) {
$tasks[$key]['position'] = $space->getPosition();
$tasks[$key]['symbol'] = $space->getSymbol();
}
Run Code Online (Sandbox Code Playgroud)
或者,
foreach ($tasks as &$task) {
$task['position'] = $space->getPosition();
$task['symbol'] = $space->getSymbol();
}
Run Code Online (Sandbox Code Playgroud)
请参阅文档:http://php.net/manual/en/control-structures.foreach.php