0

在使用 mysql 的 php 中,我怎样才能只输出两列值一次,然后循环通过其他列值。

这里:

$exe_fetch_data = mysql_query("select category, subcategory, title, body, views from table");
while($row = mysql_fetch_array($exe_fetch_data))
echo $row['category'];    //Only once
echo $row['subcategory']; //Only once

{
echo $row['title'];
echo $row['body'];
echo $row['views'];
}

期望的输出:

Category->SubCategory //Outputted only once

Title,  //Title Body and Views depend on whatever's there in the db. Could be 10 or more
Body,
Views

Title,
Body,
Views

Title,
Body,
Views
4

4 回答 4

3

这段代码应该可以解决问题

    $exe_fetch_data = mysql_query("select category, subcategory, title, body, views from table");
    $row_once = mysql_fetch_array($exe_fetch_data)
    echo $row_once['category'];    //Only once
    echo $row_once['subcategory']; //Only once

   while($row = mysql_fetch_array($exe_fetch_data)) {
    echo $row['title'];
    echo $row['body'];
    echo $row['views'];
    }

您也可以尝试使用一个初始值为初始值的标志,true并将false在第一次迭代后翻转。但我认为上面的代码会比使用标志更快,因为它不会在每次迭代后比较/检查标志值,并且使用庞大的数据库可以节省执行时间。

于 2012-11-26T06:19:46.160 回答
2

一种解决方案可能是一个布尔值,它会记住该类别是否已经输出:

$exe_fetch_data = mysql_query("select category, subcategory, title, body, views from table");
$category_output_done = false;
while($row = mysql_fetch_array($exe_fetch_data))
{
    if (!$category_output_done) {
        echo $row['category'];    //Only once
        echo $row['subcategory']; //Only once
        $category_output_done = true;
    }

    echo $row['title'];
    echo $row['body'];
    echo $row['views'];
}

另一种解决方案可能是在每次迭代时递增的计数器。

于 2012-11-26T06:17:51.753 回答
1

添加一个简单的计数器-

$counter = 0;
$exe_fetch_data = mysql_query("select category, subcategory, title, body, views from table");
while($row = mysql_fetch_array($exe_fetch_data))
if ($counter == 0){
echo $row['category'];    //Only once
echo $row['subcategory']; //Only once
$counter = 1;
}
于 2012-11-26T06:18:07.760 回答
1

由于您可能有很多结果,因此在您的 while 循环中保留一个标志是否已显示类别已经消耗 CPU。由于您总是显示具有第一个结果集的类别,因此我不会在 while 循环中保留标志,而是这样做:

$exe_fetch_data = mysql_query("select category, subcategory, title, body, views from table");
$iNrOfResults = mysql_num_rows($exe_fetch_data);
//See if the result set has any rows at all, display the categories once
if(iNrOfResults > 0)
{
    $row = mysql_fetch_array($exe_fetch_data)
    echo $row['category'];    //Only once
    echo $row['subcategory']; //Only once
    echo $row['title'];
    echo $row['body'];
    echo $row['views'];
}

//See if there are any more results, do not display the categories anymore
if(iNrOfResults > 1)
{
    while($row = mysql_fetch_array($exe_fetch_data))
    {
        echo $row['title'];
        echo $row['body'];
        echo $row['views'];
    }
}
于 2012-11-26T06:25:23.763 回答