如何使用第一列作为键将 php 多维数组转换为新数组?
我正在尝试使用数组函数(我考虑过 array_map()
或 array_walk()
,但无法让它执行我想要的操作)使用多维数组(如 MySQL 结果)创建一个数组,将数组中的字段转换为新数组的键。
假设我有一个像这样的数组:
$a = array(
0 => array( 'id' => 1, 'name' => 'john' ),
1 => array( 'id' => 28, 'name' => 'peter' )
);
我想得到另一个像这样的数组:
$b = array(
1 => array( 'name' => 'john' ),
28 => array( 'name' => 'peter' )
);
我可以用一个简单的 foreach 循环来解决它,但我想知道是否有一种更有效的方法,使用内置函数。
I'm trying to use an array function (I thought about array_map()
or array_walk()
, but couldn't get it to do what I want) in order to create an array using a multidimensional array (Like a MySQL result) turning a field from the array into the key of the new one.
Say I have an array like this one:
$a = array(
0 => array( 'id' => 1, 'name' => 'john' ),
1 => array( 'id' => 28, 'name' => 'peter' )
);
And I'd like to get another array like this:
$b = array(
1 => array( 'name' => 'john' ),
28 => array( 'name' => 'peter' )
);
I can solve it with a simple foreach loop, but I wonder whether there's a more efficient way, using a built-in function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
array_map
和array_walk
不允许您更改键。 foreach 循环绝对是最佳选择。很多时候 Foreach 甚至比 array_walk/array_map 更高效。array_map
andarray_walk
don't allow you to change keys. A foreach loop is definitely the way to go. Foreach can even be more efficient than array_walk/array_map a lot of the time.您可以使用 array_column 函数输出它接近您想要的
You Can use array_column function The Output its close to what you want
该任务实际上可以通过“无体”
foreach()
循环来完成。使用“数组解构”来定义变量和方括号推送语法,整个操作可以写在
foreach()
签名中。代码:(演示)
如果首选函数式方法,则
array_reduce()
是能够将第一级密钥写入输出数组。代码:(演示)
This task can actually be done with a "body-less"
foreach()
loop.Using "array destructuing" to define variables and square-brace pushing syntax, the entire operation can be written in the
foreach()
signature.Code: (Demo)
If a functional approach is preferred, then
array_reduce()
is capable of writing first level keys to the output array.Code: (Demo)