测试数组:
$list = [
0 => [ ‘id’ => 1001, ‘name’ => ‘张三’, ‘age’ => 20 ],
1 => [ ‘id’ => 1007, ‘name’ => ‘李四’, ‘age’ => 19 ]
];
需要实现的效果:
将数组$list 中的的键换成对应数据中‘id’的值
$list = [
1001 => [ ‘id’ => 1001, ‘name’ => ‘张三’, ‘age’ => 20 ],
1007 => [ ‘id’ => 1007, ‘name’ => ‘李四’, ‘age’ => 19 ]
];
方法1 (优选)
// 生成新的键值数组
$newKeys = array_column($list, ‘id’);
// 将数组的键设置为id
$result = array_combine($newKeys, $list);
// 打印结果
print_r($newKeys);
print_r($result);
Array (
[0] => 1001
[1] => 1007
)
Array (
[1001] => Array (
[id] => 1001
[name] => 张三
[age] => 20
)
[1007 ] => Array (
[id] => 1007
[name] => 李四
[age] => 19
)
)