在单个列表中连接表

时间:2017-01-03 18:29:55

标签: php odbc

我有两张桌子Calls& VehiclesCalls有电话号码和地址。 Vehicles有电话号码和车辆号码。 (多辆车可以通话)。我想显示所有呼叫的列表,并显示哪些单元在哪些呼叫上。

类似的东西:

Call    Address      Vehicles
1       123 Main St  A1, B3, C2
2       124 Main St  C3
3       125 Main St  A2, A3

代码:

$query = 'select calls.call, calls.address, vehicles.vehicle from calls left join vehicles on calls.call = vehicles.call';
$select = odbc_exec($conn, $query);
$while ($data = odbc_fetch_array($select)){

echo"<table>";
echo"<tr>";
echo"<td>".$data['call']."</td>";
echo"<td>".$data['address']."</td>";
echo"<td>".$data['vehicle']."</td>";
echo"</tr>";
echo"</table>";
}

当我这样做时,我会多次列出多个车辆的多个电话。如何通过逗号分隔列表中的车辆进行每次通话中的一次?

1 个答案:

答案 0 :(得分:1)

ctreeACE没有GROUP_CONCAT函数,所以在PHP中也是如此。首先创建一个关联数组,其键是电话号码。

$results = array();
$query = 'select calls.call, calls.address, vehicles.vehicle from calls left join vehicles on calls.call = vehicles.call';
$select = odbc_exec($conn, $query);
while ($data = odbc_fetch_array($select)){
    $c = $data['call'];
    if (!isset($results[$c])) {
        $results[$c] = array('call' => $c, 'address' => $data['address'], 'vehicles' => array());
    }
    if ($data['vehicle']) { // Don't append NULL vehicle that LEFT JOIN might produce if there's no matching row
        $results[$c]['vehicles'][] = $data['vehicle'];
    }
}

然后遍历它以生成表格。

echo "<table>";
foreach ($results as $call) {
    echo "<tr>";
    echo "<td>{$call['call']}</td>";
    echo "<td>{$call['address']}</td>";
    echo "<td>" . implode(', ', $call['vehicles']) . "</td>";
    echo "</tr>";
}
echo "</table>";

另请注意,您不应该在循环内启动新表,它应该在循环中。