I have an array:
我有一个数组:
[['a', 1], ['b', 1], ['c',2], ['d',2]]
How to do split it like this:
如何拆分它像这样:
[[['a', 1], ['b', 1]], [['c',2], ['d',2]]]
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:
草绘与foreach:
$in = [['a', 1], ['b', 1], ['c',2], ['d',2]];
$out = [];
foreach($in as $i) {
$out[$i[1]][] = $i;
}
2 个解决方案
#1
1
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;
#2
0
The only PHP built-in that's specific to multi-dimensional arrays seems to be array_multisort
, which won't be of much help unless there are assumptions we can make about the data contained within the input array.
唯一特定于多维数组的PHP内置似乎是array_multisort,除非我们可以对输入数组中包含的数据做出假设,否则这将没有多大帮助。
In the case of a small dataset, your brute-force example seems fine to me.
对于小型数据集,您的暴力示例对我来说似乎很好。
#1
1
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;
#2
0
The only PHP built-in that's specific to multi-dimensional arrays seems to be array_multisort
, which won't be of much help unless there are assumptions we can make about the data contained within the input array.
唯一特定于多维数组的PHP内置似乎是array_multisort,除非我们可以对输入数组中包含的数据做出假设,否则这将没有多大帮助。
In the case of a small dataset, your brute-force example seems fine to me.
对于小型数据集,您的暴力示例对我来说似乎很好。