将json数组放在第一个数组中?

时间:2017-08-11 16:49:33

标签: php arrays json

如何将$query_ppimage结果作为第一个用户查询的子数组?此时,输出在用户下输出用户,然后输出配置文件图像,而不是在用户数组内输出。因此它们没有联系。

我怎么做这样的事情? 这是我的代码:

$query_user = "SELECT *,'user' AS type FROM users WHERE username LIKE '".$query."' OR firstname LIKE '".$query."' OR lastname LIKE '".$query."'";
$quser = $conn->query($query_user);
$rows = array();
while($user = mysqli_fetch_assoc($quser)) {
    $query_ppimage = "SELECT id, post_id, relation, userID, file_format FROM media WHERE userID = '".$user['id']."' AND relation = 'profile_picture' UNION ALL SELECT -1 id, '55529055162cf' post_id, 'profile_picture' relation, '0' userID, 'jpg' file_format ORDER BY id DESC";
    $qppimg = $conn->query($query_ppimage);
    while($ppimg = mysqli_fetch_assoc($qppimg)) {
        $rows[] = $ppimg;   
        $rows[] = $user;
    }
}

以下是数组的返回方式:

[
    {
    "id": "117",
    "post_id": "1",
    "relation": "profile_picture",
    "userID": "3",
    "file_format": "jpg"
    },
    {
    "id": "3",
    "email": "casper@socialnetwk.com",
    "type": "user"
    },
]

它应该是什么样的,或类似的东西。我不认为我正确地命名了子数组,但它需要一个名称ppimage

[
    {
    "id": "3",
    "email": "casper@socialnetwk.com",
    "type": "user"
        ppimage: {
        "id": "117",
        "post_id": "1",
        "relation": "profile_picture",
        "userID": "3",
        "file_format": "jpg"
        }
    },
]

2 个答案:

答案 0 :(得分:0)

您要添加$rows两次,并附加两个单独的元素。首先尝试构建数组元素,然后将其添加到$ rows数组中。像这样:

$newrow = $user;
$newrow['ppimage'] = $ppimg;
$rows[] = $newrow;

答案 1 :(得分:0)

使用JOIN,您可以将此限制为一个查询。在循环中进行查询从不是一个好主意,如果可以,您应该避免使用它。此外,您应该使用预准备语句以防止SQL注入。

下面的代码使用JOIN,因此您只需获得一个查询 - 并构建数组,如示例所示。这是硬编码的,因为它更容易控制在哪里,因为我们现在使用JOIN,数据全部被提取(而不是在单独的变量中)。

$row = array();
$stmt = $conn->prepare("SELECT m.id, m.post_id, m.relation, m.file_format, u.id, u.email, 'user' as type
                        FROM media m 
                        JOIN users u ON u.id=m.userID 
                        WHERE m.relation = 'profile_picture' 
                          AND (username LIKE ? 
                           OR firstname LIKE ?
                           OR lastname LIKE ?)
                        ORDER BY m.id DESC");
$stmt->bind_param("sss", $query, $query, $query);
$stmt->execute();
$stmt->bind_result($mediaID, $postID, $relation, $file_format, $userID, $user_email, $type);
while ($stmt->fetch()) { // If you just expect one row, use LIMIT in the query, and remove the loop here
    $row[] = array('id' => $userID, 
                   'email' => $user_email, 
                   'type' => $type, 
                   'ppimage' => array('id' => $mediaID, 
                                      'post_id' => $postID,
                                      'relation' => $relation,
                                      'userID' => $userID,
                                      'file_format' => $file_format)
              );
}
$stmt->close();