php - 拆分数组并添加到组
问题描述
我有以下数组,它由 8 个子数组中的简单整数 (ID) 组成。我有 8 个组,我需要数组 1 中的整数进入第一组,数组 2 进入第二组,依此类推。我打算使用 sql 插入来实现这一点。
我的数据如下:
Array
(
[0] => Array
(
[0] => 4012
[1] => 3914
[2] => 4054
[3] => 3911
[4] => 4010
[5] => 3979
)
[1] => Array
(
[0] => 3916
[1] => 3946
[2] => 4059
[3] => 3924
[4] => 4018
[5] => 3967
)
[2] => Array
(
[0] => 3983
[1] => 4057
[2] => 3980
[3] => 3901
[4] => 4045
[5] => 3955
)
[3] => Array
(
[0] => 3908
[1] => 3898
[2] => 3939
[3] => 4036
[4] => 4079
[5] => 3479
)
[4] => Array
(
[0] => 3995
[1] => 3910
[2] => 4047
[3] => 3988
[4] => 3965
[5] => 4080
)
[5] => Array
(
[0] => 3925
[1] => 3561
[2] => 4000
[3] => 4061
[4] => 3950
[5] => 4058
)
[6] => Array
(
[0] => 3989
[1] => 3964
[2] => 3904
[3] => 4070
[4] => 3954
[5] => 3984
)
[7] => Array
(
[0] => 3985
[1] => 4044
[2] => 4062
[3] => 4014
[4] => 3899
)
)
我拥有的团体是:
- 01a 组
- 01b 组
- 02a 组
- 02b 组
- 03a 组
- 03b 组
- 04a 组
- 04b 组
我正在运行的 php 运行良好,因为它创建了上述组的名称,但是处理 smallgroups 数组的 foreach 不起作用。当我只想在循环中处理第一个子数组时,它将 smallusers 复制 8 次,然后是下一个。
$count = 0;
foreach ($biggroup as $key => $users) {
$smallgroups = array_chunk($users, ceil(count($users) / 8));
for ($i = 1; $i <= 4; $i++) {
$groupnum = sprintf("%02d", $count * 4 + $i);
foreach (range('a', 'b') as $letter) {
$nameofgroup = 'Group ' . $groupnum . $letter;
foreach ($smallgroups as $f => $smallusers) {
}
}
}
}
$count++;
我期待以下内容:
01A 组 4012、3914、4054、911、4010、3979
01B 组 3916、3946、4059、3924、4018、3967
ETC
解决方案
另一种方法是从biggroup
数组的索引开始生成组名。代码中的注释:
$count = 0;
foreach ($biggroup as $key => $users) { //
// defines the number
$groupnum = floor($key/2) + 1;
// the letter is decided whether the $key is even (a) or odd (b)
$letter = ($key % 2 == 0) ? 'a' : 'b';
// hence:
$nameofgroup = 'Group ' . $groupnum . $letter;
// get the array of users
$smallgroups = array_chunk($users, ceil(count($users) / 8));
// loop through them
foreach ($smallgroups as $smallusers) {
foreach ($smallusers as $u) {
// do what you need to do with each user
echo "$nameofgroup $u\n";
}
}
}
$count++;
您可以在此处查看此操作(数组大小减小):https ://eval.in/1101429
输出:
Group 1a 4012
Group 1a 3914
Group 1a 4054
Group 1a 3911
Group 1a 4010
Group 1a 3979
Group 1b 3916
Group 1b 3946
Group 1b 4059
Group 1b 3924
Group 1b 4018
Group 1b 3967
Group 2a 3983
Group 2a 4057
Group 2a 3980
Group 2a 3901
Group 2a 4045
Group 2a 3955
推荐阅读
- angular - 如何从 Angular 应用程序正确查询 MS Graph?
- php - 有没有办法解决为什么 Xdebug 没有在 VSCode 的断点处停止?
- snowflake-cloud-data-platform - 雪花存储过程 - 多个多行 SQL 命令
- java - JPA 更新 @transactional 中的子实体
- google-sheets - 在 Google 电子表格中计算列值乘以权重系数(仅当系数存在时)的总和
- python - SQLAlchemy 声明式通过辅助属性获取对象
- firebase - 将 UID 与文档字段匹配的 Firestore 规则不起作用
- ios - 电池电量检查背景
- prometheus - Prometheus 节点导出器未报告非 root 拥有的挂载
- keras - 为什么我的keras模型预测的概率总是零