从数组/ PHP获取嵌套/分层JSON

时间:2013-03-13 19:29:12

标签: php arrays json

我有一个功能:

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

1 个答案:

答案 0 :(得分:2)

首先要考虑的是循环数据集并创建所需的结构:

$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));