-2

在数据库中

row1 (type column=apple), (stage column=1)
row2 (type column=orange), (stage column=NULL)

在 PHP 中

$query = mysql_query("SELECT * from fruits");

$row = mysql_fetch_array($query);

    $num = mysql_num_rows($query);
    $i=0;
    $storeMyData = array();
    while($row = mysql_fetch_array($query))
    {
        if(isset($row['type'])){
            $type = "-" . $row['type'];
        } else {
            $type = NULL;
        }

        if(isset($row['stage'])){
            $stage = "STAGE " . $row['stage'];
        } else {
            $stage = NULL;
        }
        $fruit = implode (", ", array_filter(array($type, $stage)));

    // This will show 2 rows of data
    $storeMyData[] = $fruit;  

    // store current data in array
    $i++;
    }

    /* this will echo your storedData of loop */
    foreach($storeMyData as $prevData)

    /* or join the data using string concatenation */
    $allFinalData2 = "";

    /* this will echo your storedData of loop */
    foreach($storeMyData as $prevData)
    {
        $allFinalData2 = $allFinalData2.$prevData ;  // keep on concatenating
    }

    echo $allFinalData2;

最终输出显示为“Apple,Stage 1”“Orange,Stage”。

如果 DB 中 row2(橙色)的 stage 为 NULL,我如何在没有 Stage 的情况下显示它“Apple,Stage 1”“Orange”。

4

1 回答 1

0

更改此行

while($i < $num)

对此

while($row = mysql_fetch_array($query))

此外,不需要在循环中调用 mysql_query,使用它来防止混淆。

$type = "-" . $row['type'];
$stage = "STAGE " . $row['stage'];
于 2011-07-12T07:54:01.200 回答