[英]Php count rows and division into a group
Users create accounts and they are assigned to a group, group limit is set in advance, let's assume 5. 用户创建帐户并将其分配给一个组,预先设置了组限制,假设5。
Example: First 5 users has been saved to group_id = 1. Than how to make the 6th user have been saved to the 2nd group? 示例:前5个用户已保存到group_id =1。那么如何使第6个用户已保存到第二个组?
UserGroups::insert([
'user_id' => $user,
'game_id' => $gameId,
'group_id' => 1
]);
How to make this dynamic for some groups, like group_id = 3..4..5..6 etc ? 如何使某些组动态化,例如group_id = 3..4..5..6等?
Example code: 示例代码:
$groupSize = 2;
$allUserGroups = 4;
if($groupSize < $allUserGroups) {
UserGroups::insert([
'user_id' => $user,
'game_id' => $gameId,
'group_id' => 1
]);
} else {
UserGroups::insert([
'user_id' => $user,
'game_id' => $gameId,
'group_id' => 2
]);
}
This is only work with two groups - how to make this dynamic ? 这仅适用于两个组-如何使其动态化?
Thanks guys! 多谢你们!
<?php
$arrayUsers=['user1','user2','user3','user4','user5',
'user6','user7','user8','user9','user10',
'user11','user12','user13','user14','user15'];
$group_id=1;
echo'<pre>';
$groupedUser=array_chunk($arrayUsers, 5);
foreach($groupedUser as $data ){
$newArray[$group_id]=$data ;
$group_id++;
}
print_r($newArray);
So let's assume that your users are in the array i created. 因此,假设您的用户在我创建的数组中。 array_chunk will split them in groups of the number you want.
array_chunk将它们分成所需数量的组。 As you said in your question i splitted them in groups of 5. Then to create dynamic groups i just used a counter which i increment by one everytime my array field was full (5 records).
正如您在问题中所说的那样,我将它们分成5组。然后,我创建了一个动态组,即使用一个计数器,每当我的数组字段已满(5条记录)时,该计数器就会增加1。 In the output you will get a multidimensional array with keys the group_id and values the users.
在输出中,您将获得一个多维数组,其键为group_id并为用户赋值。
Array
(
[1] => Array
(
[0] => user1
[1] => user2
[2] => user3
[3] => user4
[4] => user5
)
[2] => Array
(
[0] => user6
[1] => user7
[2] => user8
[3] => user9
[4] => user10
)
[3] => Array
(
[0] => user11
[1] => user12
[2] => user13
[3] => user14
[4] => user15
)
)
if i understand your problem your are looking for this solution :- 如果我了解您的问题,您正在寻找此解决方案:-
$getgroups = UserGroups::select('group_id',DB::raw('count(group_id) as count'))->groupby('group_id')->get();
$getgroups = json_decode(json_encode($getgroups),true);
if(!empty($getgroups)){
end($getgroups);
$key = key($getgroups);
$group = $getgroups[$key];
if($group['count'] <5){
UserGroups::insert([
'user_id' => $user,
'game_id' => $gameId,
'group_id' => $group['group_id']
]);
}else{
$groupvalue = $group['group_id'] +1;
UserGroups::insert([
'user_id' => $user,
'game_id' => $gameId,
'group_id' => $groupvalue
]);
}
}else{
UserGroups::insert([
'user_id' => $user,
'game_id' => $gameId,
'group_id' => 1
]);
}
echo "saved"; die;
I have tested its working perfectly. 我已经测试了它的完美工作。 Good luck for your project :)
祝您的项目好运:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.