如何使用第一列作为键将 php 多维数组转换为新数组?

发布于 2024-10-09 19:00:21 字数 512 浏览 0 评论 0原文

我正在尝试使用数组函数(我考虑过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

紫罗兰の梦幻 2024-10-16 19:00:21

array_maparray_walk 不允许您更改键。 foreach 循环绝对是最佳选择。很多时候 Foreach 甚至比 array_walk/array_map 更高效。

array_map and array_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.

泪是无色的血 2024-10-16 19:00:21

您可以使用 array_column 函数输出它接近您想要的

array_column($a, null, 'id')

You Can use array_column function The Output its close to what you want

array_column($a, null, 'id')
肤浅与狂妄 2024-10-16 19:00:21

该任务实际上可以通过“无体”foreach() 循环来完成。

使用“数组解构”来定义变量和方括号推送语法,整个操作可以写在 foreach() 签名中。

代码:(演示

$result = [];
foreach ($a as ['id' => $id, 'name' => $result[$id]['name']]);

var_export($result);

如果首选函数式方法,则 array_reduce() 是能够将第一级密钥写入输出数组。

代码:(演示)

var_export(
    array_reduce(
        $a,
        fn($result, $row) => array_replace($result, [$row['id'] => ['name' => $row['name']]]), 
        []
    )
);

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)

$result = [];
foreach ($a as ['id' => $id, 'name' => $result[$id]['name']]);

var_export($result);

If a functional approach is preferred, then array_reduce() is capable of writing first level keys to the output array.

Code: (Demo)

var_export(
    array_reduce(
        $a,
        fn($result, $row) => array_replace($result, [$row['id'] => ['name' => $row['name']]]), 
        []
    )
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文