0

我有一个有点复杂的 php sql 查询,我需要将其放入 JSON 中以发送回我的终端。有人可以帮忙吗?我一直在为此苦苦挣扎,似乎无法做到正确。我的代码是这样的:

//Grab all people living in a city, and for each of those people, grab all of their carsmodel and license plate.  My output should be something like [{"firstname":John, "lastname":Smith, "cars":[car1, car2, car3...], "plates":[plate1, plate2, ...]},{"firstname":Jack,"lastname":Hide, "cars":[car1, car2, car3], "plates":[plate1, plate2,...]}]
$sql = "SELECT id, firstname, lastname FROM residents WHERE residents.city = ?";
$q = $connection->prepare($sql);
$q->execute(array($city));

while($row = $q->fetch())
{
    $sql2 = "SELECT carid FROM cars WHERE userid = ?"
    $q2 = $connection->prepare($sql2);
    $q2->execute(array($row[0]));
    while($row2 = $q2->fetch())
    {
        // What do I do here?!
    }
}

return json_encode(//?); 

任何帮助都非常感谢!

谢谢!

4

2 回答 2

1

我会将获取模式设置为PDO::FETCH_OBJ(或PDO::FETCH_ASSOC)而不是使用数字。您可以在连接上执行此操作,也可以fetch.

$q2 = $connection->prepare("SELECT carid FROM cars WHERE userid = ?");
$users = array();
while ($row = $q->fetch(PDO::FETCH_OBJ)) {
    $q2->execute(array($row->id));
    $row->cars = $q2->fetchall(PDO::FETCH_OBJ);
    $users[] = $row;
}
return json_encode($users);
于 2013-03-29T22:07:29.817 回答
1

在一个查询中进行:

SELECT id, firstname, lastname, carid -- and perhaps other cars columns here
FROM residents
INNER JOIN cars
ON cars.userid = residents.id
WHERE residents.city = ?
ORDER BY residents.id

然后在 PHP 部分:

$data = array();
$current = array();
while($row2 = $q2->fetch())
{
    if ($current['id'] != $row[0]) {
        $data[] = $current;          
        $current = array('id' => $row[0], 'firstname' => $row[1], 'lastname' => $row[2] );
    } else {
        $current['cars'][] = array( /* row data for car */ );
    }
}
array_shift($data);
return json_encode($data);
于 2013-03-29T22:20:54.680 回答