根据列值对子数组进行分组 [英] Group subarrays based on column value

查看:50
本文介绍了根据列值对子数组进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

[['a', 1], ['b', 1], ['c',2], ['d',2]]

如何根据第二列值将子数组分组,如下所示:

How can I group the subarrays based on the second column value like this:

[[['a', 1], ['b', 1]], [['c',2], ['d',2]]]

我有一个想法可以用foreach来解决,但是内置函数可能有办法吗?

I have an idea to solve this with a foreach, but it may have a way with the built-in functions?

用foreach草图:

Sketch with foreach:

$in = [['a', 1], ['b', 1], ['c',2], ['d',2]];
$out = [];

foreach($in as $i) {
    $out[$i[1]][] = $i;
}

推荐答案

您或多或少都拥有解决方案.

You more or less have what I would have arrived at for a solution.

只要您希望用作索引的数据始终位于数组中的相同位置,就可以像在收集器数组中一样对索引进行硬编码.

As long as the data that you wish to use as an index will always be in the same position in the array, you will be able to hardcode the index as you have done in the collector array.

如果没有,我会考虑移动到关联数组,并在创建数组时为要用作索引的值分配名称.

If not, I would think about moving to an associative array and assigning a name to the value that you want to use as an index when creating the array.

[['a', 'index'=>1] [etc...]]

$out[$i[index]][] = $i;

这篇关于根据列值对子数组进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆