0

我的代码包含两列,如下所示:

社区 1
餐厅 1


社区 1
餐厅 2


社区 1
餐厅 3


我想要:

邻里 1
餐厅 1
餐厅 2
餐厅 3


$result = mysql_query("SELECT ID,RName,NHood FROM Restaurants ORDER BY NHood ASC, TRIM(LEADING 'The ' FROM RName) ASC",$connect);
$numRows = mysql_num_rows($result);
$middleIndex = (int)(($numRows+1) / 2);

$names = array();
while($row = mysql_fetch_assoc($result)) {
    $names[] = $row['RName'];
    $id[] = $row['ID'];
    $hood[] = $row['NHood'];
}

// print the left column
echo "<table>";
echo "<tr>";
echo "<td width=60%>";
echo "<div id=\"left\">\n";
for($i = 0; $i < $middleIndex; $i++) {
    echo $hood[$i];
    echo "<p><a href=\"Restaurant.php?ID=".$id[$i]."\">$names[$i]</a></p>\n";
}
echo "</div>\n";
echo "</td>";

// print the right column
echo "<td>";
echo "<div id=\"right\">\n";
for($i = $middleIndex; $i < $numRows; $i++) {
    echo $hood[$i];
        echo "<p><a href=\"Restaurant.php?ID=".$id[$i]."\">$names[$i]</a></p>\n";
}
echo "</div>\n";  
echo "</tr>";
echo "</table>";
4

1 回答 1

1

这是您想要的逻辑(伪代码):

SELECT
    ID,
    RName,
    NHood
FROM
    Restaurants
ORDER BY
    NHood ASC, RName ASC

这应该返回首先按附近排序的结果列表,然后按餐厅名称排序。

接下来,您将逐行处理这些结果,以创建一个嵌套数组,其中包含您想要用于视图的数据结构:

$neighborhoods = array();

foreach($result as $row)
{
    // Add each restaurant to a list named for the current neighborhood
    $neighborhoods[$row['NHood']][] = $row['RName'];
}

这将产生一个像这样的数据结构:

$neighborhoods = array(
    'neighborhood1' => array(
        'restaurant1',
        'restaurant2',
        'restaurant3',
    ),
    'neighborhood2' => array(
        'restaurant1',
        'restaurant2',
    ),
)

然后您将通过执行以下操作来使用它:

foreach($neighborhoods as $neighborhood => $restaurants)
{
    echo $neighborhood;
    foreach($restaurants as $restaurant)
    {
        echo $restaurant;
    }
}

如果您的列表真的很大并且您担心内存,那么实现会有所不同,但逻辑是相同的。这种技术速度更快,但读取和维护有点困难,因为表示层和数据层逻辑都混合在一起:

$currentNH = null;

while($row = fetch_row($results))
{
    // Detect when the neighborhood changes
    if($currentNH != $row['NHood']) {
        echo $row['NHood'];
    }

    echo $row['RName'];
}
于 2012-12-27T02:54:34.703 回答