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"}
        ]
]

助けてくれてありがとう。

Postgresql9.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 に答える