0

我有一个功能:

function getROLES() {
    $sql = "
SELECT wur.role_id, wur.user_id, wu.first_name, wu.last_name
FROM user_roles wur LEFT JOIN users wu ON wur.user_id = wu.user_id
WHERE wur.role_id IN (100,101)
    ";
    try {
        $db = getConnection();
        $stmt = $db->query($sql);  
        $roles = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $db = null;
        echo json_encode($roles);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

这个函数的输出是一个数组和 JSON

大批:

Array ( 
    [0] => Array 
        ( [role_id] => 100 [user_id] => 1 [first_name] => Al [last_name] => Pacino ) 
    [1] => Array 
        ( [role_id] => 100 [user_id] => 5 [first_name] => Brad [last_name] => Pitt ) 
    [2] => Array 
        ( [role_id] => 101 [user_id] => 12 [first_name] => Pierce [last_name] => Brosnan ) 
    [3] => Array 
        ( [role_id] => 101 [user_id] => 10 [first_name] => Johnny [last_name] => Deep ) 
    [4] => Array 
        ( [role_id] => 101 [user_id] => 11 [first_name] => Tom [last_name] => Hanks ) 
) 1

JSON:

[
    {"role_id":100,"user_id":1,"first_name":"Al","last_name":"Pacino"},
    {"role_id":100,"user_id":5,"first_name":"Brad","last_name":"Pitt"},
    {"role_id":101,"user_id":12,"first_name":"Pierce","last_name":"Brosnan"},
    {"role_id":101,"user_id":10,"first_name":"Johnny","last_name":"Deep"},
    {"role_id":101,"user_id":11,"first_name":"Tom","last_name":"Hanks"}
]

问题是:如何识别组中所有用户属于每个role_id。如何转换或更改输出 JSON 上的代码,如下所示:

[
    {"role_id":100, "childrens":
        [
            {"user_id":1,"first_name":"Al","last_name":"Pacino"},
            {"user_id":5,"first_name":"Brad","last_name":"Pitt"}
        ],
    {"role_id":101, "childrens":    
        [
            {"user_id":12,"first_name":"Pierce","last_name":"Brosnan"},
            {"user_id":10,"first_name":"Johnny","last_name":"Deep"},
            {"user_id":11,"first_name":"Tom","last_name":"Hanks"}
        ]
]

提前感谢您的帮助。

请注意,我使用的是 Postgresql 9.1.8

4

1 回答 1

2

好吧,有些人首先想到的是 jsut 循环遍历数据集并创建所需的结构:

$jsonRoles = array();

foreach($roles as $role) {
   $id = $role['role_id'];
   if(!isset($jsonRoles[$id])) {
      $jsonRoles[$id] = array(
          'role_id' => $id,
          'childrens' => array()
      );
   }
   unset($role['role_id']);
   $jsonRoles[$id]['childrens'][] = $role;
}

// then to get a regular array use array values:
echo json_encode(array_values($jsonRoles));
于 2013-03-13T19:38:18.407 回答