有没有办法创建一个行匹配的组?很难解释但是尝试不好。
如果我有这些字段的数据库:
ID: Name: GROUP_ID:
1 Jacob 1
2 Jonathan 1
3 Jesper 2
4 Jeod 2
5 Jeod 3
我有一个使用PDOStatement::fetchAll
$users = $page->retrieve_users();
然后我希望每个GROUP_ID
都在一个分组的div中。
现在显示所有名称
foreach($users as $user){
echo "<div>".$user["name"]."</div>";
}
如何对其进行配置,以使具有相同user["name"]
的每个GROUP_ID
都在自己的div中?
我知道我必须为每个不同的GROUP_ID
创建一个新数组,但我甚至不知道如何做到这一点因为我希望它具有灵活性意味着如果我添加一个具有唯一{{1}的新用户它将被分类为自己的。
任何人都可以帮我吗?
提前致谢!
答案 0 :(得分:2)
示例代码
$groups = array();
foreach($users as $user){
$group = $user["GROUP_ID"];
if(!array_key_exists($group,$groups)){
$groups[$group] = array();
}
$groups[$group][] = $user["name"];
}
foreach($groups as $group => $members){
echo "This is group $group\n";
foreach($members as $username){
echo $username."\n";
}
}
答案 1 :(得分:0)
$usersByGroup = array();
foreach($users as $user) {
$usersByGroup[$user['group_id']][] = $user['user'];
}
此数组如下所示:
array(
1 => array("Jacob", "Jonathan" ),
2 => array("Jesper", "Jeod" ),
3 => array("Jeod")
)
答案 2 :(得分:0)
$user_name_array = array();
foreach ($users as $user) {
$user_name_array[$user['GROUP_ID']][] = $user['Name'];
}
foreach ($user_name_array as $group_id => $user_names) {
foreach ($user_names as $user_name) {
echo "<div>$user_name</div>\n";
}
}