我遇到了这个PHP函数的问题,我正在尝试用他的角色和组来获取用户,它与角色合作很好,但是我对组有问题,因为我得到的阵列有相同的组,当然是我的想要是重复的自由数组。我理解为什么我得到这个,因为我的用户有2个角色,我让他在sql查询2次,谁能解释我什么是最佳做法以及如何避免这种情况,如果我使用这样的查询,或者我可以使用另一个查询,我将找到成员的所有组,然后将它放在该数组中,但这是一个函数中的2个DB调用,它可能不是那么好的解决方案。
function getAll($mysqli) {
$stmt = $mysqli->prepare("SELECT u.id, u.firstName, u.lastName, u.email,
u.phoneNumber, u.address, u.birthDate, ur.roleName, cg.id, cg.name FROM users as u
LEFT OUTER JOIN user_role as ur ON u.id = ur.userId
LEFT OUTER JOIN user_group as ug on ug.userId = u.id
LEFT OUTER JOIN control_group as cg on cg.id = ug.groupId");
$stmt->execute();
$stmt->bind_result($id, $firstName, $lastName, $email, $phoneNumber,
$address, $birthDate, $roleName, $groupId, $groupName);
$users = array();
while ($stmt->fetch()) {
if (empty($users[$id])) {
$users[$id] = array(
'id' => $id,
'firstName' => $firstName,
'lastName' => $lastName,
'email' => $email,
'phoneNumber' => $phoneNumber,
'address' => $address,
'birthDate' => $birthDate,
'roles' => array(),
'groups' => array()
);
}
if ($roleName) {
$users[$id]['roles'][] = array(
'roleName' => $roleName
);
}
if ($groupId) {
$users[$id]['groups'][] = array(
'groupName' => $groupName
);
}
}
$stmt->close();
$mysqli->close();;
echo json_encode($users);
}
当我执行该功能时,我会得到这样的回复
{
"1":{
"id":1,
"firstName":"John",
"lastName":"Doe",
"email":"john@email.com",
"phoneNumber":"062-441234-123123",
"address":"Some Address 40\/2",
"birthDate":"1989-12-29",
"roles":[
{
"roleName":"Admin"
},
{
"roleName":"User"
}
],
"groups":[
{
"groupName":"Group 1"
},
{
"groupName":"Group 1"
}
]
},
"2":{
"id":2,
"firstName":"Jane",
"lastName":"Doe",
"email":"jane@email.com",
"phoneNumber":"0112-11121-221322",
"address":"Address 21ca",
"birthDate":"1975-12-28",
"roles":[
{
"roleName":"Admin"
},
{
"roleName":"User"
}
],
"groups":[
]
}
}
答案 0 :(得分:1)
您可以在将角色(或组)插入数组之前检查它是否已存在:
if ($roleName) {
$found = false;
foreach ($users[$id]['roles'] as $role) {
if($role['roleName'] == $roleName){
$found = true;
break;
}
}
if($found == false)
$users[$id]['roles'][] = array(
'roleName' => $roleName
);
}
请注意,我根据您的结构给出了答案。但我强烈建议改变数组的结构,以便像O(1)
编辑:为了完成我的回答:我想说JSON结构并不反映真实情况。您声明用户具有角色和组,这是真的,但角色属于该组。用户可以是组1中的ADMIN和组2中的ANYTHING。这就是为什么我认为你应该输出的是这样的:
{
"1":{
"id":1,
"firstName":"John",
"lastName":"Doe",
"email":"john@email.com",
"phoneNumber":"062-441234-123123",
"address":"Some Address 40\/2",
"birthDate":"1989-12-29",
"groups":[
{
"groupName": "Group 1",
"roles": [
{
"roleName":"Admin"
},
{
"roleName":"User"
}
]
}
]
},
"2":{
"id":2,
"firstName":"Jane",
"lastName":"Doe",
"email":"jane@email.com",
"phoneNumber":"0112-11121-221322",
"address":"Address 21ca",
"birthDate":"1975-12-28",
"groups":[
]
}
}