You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何引用变量的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 22:40:15