我有一个数组,它包含其他关联数组作为它的值.这些"子"数组中的每一个都使用键-值对进行映射:
$items = [
['type' => 1, 'text' => 'A'],
['type' => 2, 'text' => 'B'],
['type' => 2, 'text' => 'C'],
['type' => 3, 'text' => 'D'],
['type' => 2, 'text' => 'E'],
['type' => 1, 'text' => 'F'],
['type' => 4, 'text' => 'G'],
['type' => 2, 'text' => 'H'],
['type' => 1, 'text' => 'I'],
['type' => 4, 'text' => 'J'],
['type' => 2, 'text' => 'K'],
['type' => 4, 'text' => 'L'],
['type' => 2, 'text' => 'M'],
['type' => 3, 'text' => 'N'],
['type' => 3, 'text' => 'O'],
['type' => 1, 'text' => 'P'],
['type' => 1, 'text' => 'Q'],
['type' => 2, 'text' => 'R'],
['type' => 3, 'text' => 'S'],
['type' => 2, 'text' => 'T'],
['type' => 3, 'text' => 'U'],
['type' => 2, 'text' => 'V'],
['type' => 3, 'text' => 'W'],
['type' => 2, 'text' => 'X'],
['type' => 4, 'text' => 'Y'],
['type' => 2, 'text' => 'Z'],
];
如何对此数组进行排序并返回为另一个数组,并满足以下要求?
- 它需要按其
type
对关联数组进行排序. - 它需要 Select 显示在
$items
数组中的前3项,然后移到下一种类型,即2
,并执行相同的操作.在我的代码中,types
的最大值是8
,但理论上它应该适用于任何数字. - 如果它一次 Select 了每种类型的3个,则使用数组中的其余项再次重新启动,再次从类型
1
开始.
本质上,您应该获得另一个数组,该数组从上到下以交替的顺序具有其类型的值,如下所示:
[
['type' => 1, 'text' => 'A'],
['type' => 1, 'text' => 'F'],
['type' => 1, 'text' => 'I'],
['type' => 2, 'text' => 'B'],
['type' => 2, 'text' => 'C'],
['type' => 2, 'text' => 'E'],
['type' => 3, 'text' => 'D'],
['type' => 3, 'text' => 'N'],
['type' => 3, 'text' => 'O'],
['type' => 4, 'text' => 'G'],
['type' => 4, 'text' => 'J'],
['type' => 4, 'text' => 'L'],
['type' => 1, 'text' => 'P'],
['type' => 1, 'text' => 'Q'],
['type' => 2, 'text' => 'H'],
['type' => 2, 'text' => 'K'],
['type' => 2, 'text' => 'M'],
['type' => 3, 'text' => 'S'],
['type' => 3, 'text' => 'U'],
['type' => 3, 'text' => 'W'],
['type' => 4, 'text' => 'Y'],
['type' => 2, 'text' => 'R'],
['type' => 2, 'text' => 'T'],
['type' => 2, 'text' => 'V'],
['type' => 2, 'text' => 'X'],
['type' => 2, 'text' => 'Z'],
]
text
对排序并不重要.
事实上,我甚至制作了一段YouTube视频,以更好地解释应该发生什么:Video
我目前的 idea 是使用一个名为$groups
的独立数组,使用一个foreach
循环八次,如果不是针对特定类型,则在每一次循环中继续循环.例如:
// My above $items array example here
// Initialize $groups
$groups = [];
// foreach for type 1
foreach ($items as $item) {
// If any of the items are not of type 1, ignore and continue
if ($item["type"] !== 1) {
continue;
}
// Otherwise, push to $groups
array_push($groups, $item["type"];
}
// foreach for type 2
foreach ($items as $item) {
// If any of the items are not of type 2, ignore and continue
if ($item["type"] !== 2) {
continue;
}
// Otherwise, push to $groups
array_push($groups, $item["type"];
}
// Do this for each possible type, up to type 8
这不仅看起来非常低效和倒退,我只是觉得有更好的方法来做,或者从另一个我错过的Angular go 做.我不相信上面的代码接近解决方案.