如何将PDO :: FETCH_NUM正确格式化为JSON结果

时间:2014-02-25 03:52:12

标签: php json pdo

我正在返回这样的JSON文档:

ug_gpid: [[4], [2], [3]]

这不是预期的格式,我希望如此:

ug_gpid: [4, 2, 3]

这是我的代码:

$user = json_decode($resp, true);
$sql = "SELECT ug_gpid FROM user_group WHERE ug_usid =:id AND ug_status = 1";

try {
    $db = getConnection();
    $stmt = $db->prepare($sql);
    foreach ($user as $item => $value) {
        $newUser[$item] = $value;
        $stmt->bindParam("id", $value["us_id"]);
        $stmt->execute();
        $ugroup = $stmt->fetchAll(PDO::FETCH_NUM);
        $newUser[$item]['ug_gpid'] = $ugroup;
    }
    $db = null;
    $response = $app->response();
    $response->header('Content-Type', 'application/json');
    echo json_encode($newUser, JSON_NUMERIC_CHECK);     
} catch(PDOException $e) {                  
    $error = array("queryGroupError"=> array("text"=>$e->getMessage()));
    echo json_encode($error); 
}

我将结果存储在$ugroup中。如何实现所需的输出?

2 个答案:

答案 0 :(得分:2)

问题是PDOStatement::fetchAll返回一个数组数组。您想构建一个单值的平面数组。

我会改用它......

$stmt = $db->prepare($sql);
$stmt->bindParam(':id', $us_id);
foreach ($user as $item => $value) {
    $newUser[$item] = $value;
    $us_id = $value['us_id']; // this is for the bind
    $stmt->execute();
    while ($gpid = $stmt->fetchColumn()) {
        $newUser[$item]['ug_gpid'][] = $gpid;
    }
}

答案 1 :(得分:1)

它没有按预期工作的原因已经得到解答;但是,使用单个查询会更有效:

$sql = sprintf(
    "SELECT ug_usid, GROUP_CONCAT(ug_gpid)
       FROM user_group 
       WHERE ug_usid IN (%s) AND ug_status = 1
       GROUP BY ug_usid",
    str_pad('?', count($user) * 2 - 1, ',?');
);

// ...

// run query and build search result map
$stmt = $db->prepare($sql);
$stmt->execute(array_column($user, 'us_id'));
$groups = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

// extend user information with search results
array_walk($user, function(&$u) use ($groups) {
    if (isset($groups[$user['us_id']])) {
        $u['ug_gpid'] = explode(',', $groups[$user['us_id']]);
    } else {
        $u['ug_gpid'] = [];
    }
});

echo json_encode($user, JSON_NUMERIC_CHECK);

请注意,它假设您使用MySQL作为数据库引擎,因为它使用GROUP_CONCAT这是SQL的MySQL扩展。