对象数组返回相同的值 [英] Array of objects returns same values

查看:87
本文介绍了对象数组返回相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此功能返回具有角色和组的用户.

I use this function to return users with their roles and groups.

我想返回具有正确索引的对象数组,这就是我创建$ index计数器的原因.

I want to return array of objects with correct index, that is reason why I created $index counter.

这里的问题是,如果一个用户有多于1个群组,我将获得重复的用户.

Problem here is that I get duplicate users if one user have more then 1 groups.

例如,如果我有一个用户具有3个组,那么我将获得该用户3次.

So for example if I have one user with 3 groups, I will get that user 3 times.

如何避免重复用户?

我知道我需要以某种方式检查该用户是否已经存在,就像我检查角色一样,但是我不确定在哪里.

I know that somehow I need to check if that user already exists, like I checked for roles, but I'm not sure where.

如果我将users ['$ index']替换为users ['$ id'],此代码将起作用,但那样一来,我将无法获得具有正确索引的数组,而这正是我所需要的.

This code will work if I replace users['$index'] with users['$id'] but on that way I won't get array with correct index, and that is what I need.

    $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
      JOIN user_role as ur 
         ON u.id = ur.userId 
      LEFT 
      JOIN user_group as ug 
         on ug.userId = u.id 
      LEFT 
      JOIN control_group as cg 
         on cg.id = ug.groupId 
     WHERE u.id != ?");
    $stmt->bind_param("i", $_SESSION["id"]);
    $stmt->execute();
    $stmt->bind_result($id, $firstName, $lastName, $email, $phoneNumber, 
        $address, $birthDate, $roleName, $groupId, $groupName);
    $users = array();

    $index = 0;

    while ($stmt->fetch()) {
        if (empty($users[$index])) {
            $users[$index] = array(
                'id' => $id,
                'firstName' => $firstName,
                'lastName' => $lastName,
                'email' => $email,
                'phoneNumber' => $phoneNumber,
                'address' => $address,
                'birthDate' => $birthDate,
                'roles' => array(),
                'groups' => array()
            );
        }
        if ($roleName) {
            $found = false;
            foreach ($users[$index]['roles'] as $role) {
                if($role['roleName'] == $roleName){
                    $found = true;
                    break;
                }
            }
            if($found == false)
                $users[$index]['roles'][] = array(
                    'roleName' => $roleName
                );
         }

        if ($groupId) {
            $found = false;
            foreach ($users[$index]['groups'] as $group) {
                if($group['groupName'] == $groupName){
                    $found = true;
                    break;
                }
            }
            if($found == false)
                $users[$index]['groups'][] = array(
                    'groupName' => $groupName
                );
         }
         $index++;
    }

    $stmt->close();
    $mysqli->close();
    echo json_encode($users);

所以基本上我希望有这样的对象

So basically i expect object like this

{  
      "id":2,
      "firstName":"Jon",
      "lastName":"Doe",
      "email":"jon.doe@email.com",
      "phoneNumber":"0621-123-444",
      "address":"Address 12a",
      "birthDate":"1976-01-01",
      "roles":['list of role objects'],
      "groups":['list of group objects']
   }

我也不知道我是否以正确的方式生成对象,我想知道是否有人可以告诉我什么是正确的方法以及如何正确生成像这样的对象.

Also i'm not sure if i'm generating object on correct way, i would like if someone can tell me what is right approach and how to properly generate object like this one.

推荐答案

如果可以执行多个查询,则可以首先获取所有用户,然后为每个用户分配角色和组.

If performing multiple queries is an option you could first get all users and then per user the roles and groups.

$user_stmt = $mysqli->prepare("SELECT id, firstName, lastName, email, phoneNumber, address, birthDate FROM users WHERE id != ?");
$user_stmt->bind_param("i", $_SESSION["id"]);
$user_stmt->execute();
$user_stmt->bind_result($id, $firstName, $lastName, $email, $phoneNumber, $address, $birthDate);

$role_stmt = $mysqli->prepare("SELECT roleName FROM user_role WHERE userId = ?");
$group_stmt = ...

$users = array();

while($user_stmt->fetch())
{
    $role_stmt->bind_param("i", $id);
    $role_stmt->execute();
    $role_stmt->bind_result($roleName);

    $roles = array();

    while($role_stmt->fetch())
    {
        $roles[] = array("roleName" => $roleName);
    }

    $groups = array();

    // Same as for roles

    $users[] = array(
            'id' => $id,
            'firstName' => $firstName,
            'lastName' => $lastName,
            'email' => $email,
            'phoneNumber' => $phoneNumber,
            'address' => $address,
            'birthDate' => $birthDate,
            'roles' => $roles,
            'groups' => $groups
        );
    }
}

$user_stmt->close();
$role_stmt->close();
$group_stmt->close();
$mysqli->close();
echo json_encode($users);

这篇关于对象数组返回相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆