为何引用变量的unset操作未生效?PHP数组重排问题求助
问题描述
需要将以下索引数组:
$items = [ [ 'key' => '1', 'id' => 'a' ], [ 'key' => '2', 'id' => 'b' ] ];
转换为以id值为键的关联数组:
$items = [ 'a' => [ 'key' => '1', 'id' => 'a' ], 'b' => [ 'key' => '2', 'id' => 'b' ] ];
使用了以下代码实现,但执行后原索引[0]、[1]元素未被移除:
foreach($items as &$item){ $items[$item['id']] = $item; unset($item); } print_r($items);
执行结果:
Array ( [0] => Array ( [key] => 1 [id] => a ) [1] => Array ( [key] => 2 [id] => b ) [a] => Array ( [key] => 1 [id] => a ) [b] => Array ( [key] => 2 [id] => b ) )
错误原因
你误解了unset($item)的作用:
- 在foreach循环中,
&$item是当前循环元素的引用变量,unset($item)只是销毁了这个引用变量本身,并没有从原数组$items中移除对应的索引(0、1)元素。 - 你的代码只是给数组新增了
a、b键的元素,原索引元素完全没被处理,所以会保留下来。
正确实现方法
方法1:创建新数组(推荐,避免遍历原数组时修改结构引发的问题)
$newItems = []; foreach ($items as $item) { $newItems[$item['id']] = $item; } print_r($newItems);
方法2:遍历原数组的键,直接删除原索引
foreach ($items as $key => $item) { $items[$item['id']] = $item; unset($items[$key]); // 这里删除的是原数组的索引键(0、1) } print_r($items);
方法3:使用array_column(PHP 5.5+,最简写法)
$items = array_column($items, null, 'id'); print_r($items);
内容的提问来源于stack exchange,提问作者Arpit Jain
相关产品推荐
相关产品推荐

