簡體   English   中英

從數據庫中獲取記錄時的動態行跨度

[英]Dynamic rowspan while fetching records from database

Ename   Sal      
tom     100
tom     200
bill    100
bill    250
bill    450
bill    400

這是查詢和 html 結構,它給出了上述 output。

<?php 
$sql = "select * from emp ";
$result= mysql_query($sql);
while($row=mysql_fetch_array($result))
{
  <tr >
    <td rowspan=""  ><?php echo $row['ename']; ?></td>
    <td><?php echo $row['esal']?></td>
  </tr>
  <? }?>

我怎樣才能關注 output:

Ename   Sal      
tom     100
        200
bill    100
        250
        450
        400

對不起我糟糕的英語:在這里我回答了這個問題How to show data from database with dynamic rowspan 讓我再次嘗試回答這個問題。 首先,以免我們處理 mysql 查詢。

MySql 工作:

在 mysql 查詢中,您尚未查詢 order by。 因為在現實生活中,你不能指望在所有的湯姆、賬單記錄之后。 例如采取以下插入。

INSERT INTO test_work(ename, sal) 
               VALUES("tom",  100), 
                     ("bill", 450), 
                     ("bill", 100), 
                     ("tom",  200),
                     ("bill", 250),
                     ("bill", 400),
                     ("James", 50);
SELECT * FROM test_work;

結果:

+-------+------+
| ename | sal  |
+-------+------+
| tom   |  100 |
| bill  |  450 |
| bill  |  100 |
| tom   |  200 |
| bill  |  250 |
| bill  |  400 |
| James |   50 |
+-------+------+

因此,您的 mysql 查詢應按 ename 排序。 這里也應該訂購每個人的sal 所以我們的查詢:

SELECT * FROM emp ORDER BY ename, sal;

編碼:

  1. 整個任務我們可以分為 3 個部分。
    1. Mysql 數據獲取和存儲在數組中。
    2. 計算行跨度
    3. 印刷

MySql 數據獲取:

在從 mysql 服務器獲取數據期間,我們應該嘗試使用 mysql_fetch_assoc function 而不是 mysql_fetch_array。 因為mysql_fetch_assoc 只會返回ename 和sal。 但是 mysql_fetch_array 將返回索引為 ename、sal、0、1 的數組。

    # connect to mysql server
    # and select the database, on which
    # we will work.
    $conn = mysql_connect('', 'root', '');
    $db   = mysql_select_db('test');

    # Query the data from database.
    $query  = 'SELECT * FROM test_work ORDER BY ename, sal';
    $result = mysql_query($query);

    # Intialize the array, which will 
    # store the fetched data.
    $sal = array();
    $emp = array();

    # Loop over all the fetched data, and save the
    # data in array.
    while($row = mysql_fetch_assoc($result)) {
        array_push($emp, $row['ename']);
        array_push($sal, $row['sal']);
    }

計算行跨度:

    # Intialize the array, which will store the 
    # rowspan for the user.
    $arr = array();

    # loop over all the sal array
    for ($i = 0; $i < sizeof($sal); $i++) {
        $empName = $emp[$i];

        # If there is no array for the employee
        # then create a elemnt.
        if (!isset($arr[$empName])) {
            $arr[$empName] = array();
            $arr[$empName]['rowspan'] = 0;
        }

        $arr[$empName]['printed'] = "no";

        # Increment the row span value.
        $arr[$empName]['rowspan'] += 1;
    }

當您將 print_r 數組 output 將是:

Array
(
    [bill] => Array
        (
            [rowspan] => 4
            [printed] => no
        )

    [James] => Array
        (
            [rowspan] => 1
            [printed] => no
        )

    [tom] => Array
        (
            [rowspan] => 2
            [printed] => no
        )

)

使用行跨度打印:

    echo "<table cellspacing='0' cellpadding='0'>
            <tr>
                <th>Ename</th>
                <th>Sal</th>
            </tr>";


    for($i=0; $i < sizeof($sal); $i++) {
        $empName = $emp[$i];
        echo "<tr>";

        # If this row is not printed then print.
        # and make the printed value to "yes", so that
        # next time it will not printed.
        if ($arr[$empName]['printed'] == 'no') {
            echo "<td rowspan='".$arr[$empName]['rowspan']."'>".$empName."</td>";
            $arr[$empName]['printed'] = 'yes';
        }
        echo "<td>".$sal[$i]."</td>";
        echo "</tr>";
    }
    echo "</table>";

代碼優化:

現在我們可以結合行跨度計算和 mysql 數據獲取。 因為在將獲取的數據保存在數組中的過程中,我們可以計算行跨度。 所以我們的最終代碼:

<!DOCTYPE html>
<html>
    <head>
        <style>
            table tr td, table tr th{
                border: black 1px solid;
                padding: 5px;
            }
        </style>
    </head>
    <body>
        <?php
        # connect to mysql server
        # and select the database, on which
        # we will work.
        $conn = mysql_connect('', 'root', '');
        $db   = mysql_select_db('test');

        # Query the data from database.
        $query  = 'SELECT * FROM test_work ORDER BY ename, sal';
        $result = mysql_query($query);

        # $arr is array which will be help ful during 
        # printing
        $arr = array();

        # Intialize the array, which will 
        # store the fetched data.
        $sal = array();
        $emp = array();

        #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
        #     data saving and rowspan calculation        #
        #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#

        # Loop over all the fetched data, and save the
        # data.
        while($row = mysql_fetch_assoc($result)) {
            array_push($emp, $row['ename']);
            array_push($sal, $row['sal']);

            if (!isset($arr[$row['ename']])) {
                $arr[$row['ename']]['rowspan'] = 0;
            }
            $arr[$row['ename']]['printed'] = 'no';
            $arr[$row['ename']]['rowspan'] += 1;
        }


        #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        #        DATA PRINTING             #
        #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
        echo "<table cellspacing='0' cellpadding='0'>
                <tr>
                    <th>Ename</th>
                    <th>Sal</th>
                </tr>";


        for($i=0; $i < sizeof($sal); $i++) {
            $empName = $emp[$i];
            echo "<tr>";

            # If this row is not printed then print.
            # and make the printed value to "yes", so that
            # next time it will not printed.
            if ($arr[$empName]['printed'] == 'no') {
                echo "<td rowspan='".$arr[$empName]['rowspan']."'>".$empName."</td>";
                $arr[$empName]['printed'] = 'yes';
            }
            echo "<td>".$sal[$i]."</td>";
            echo "</tr>";
        }
        echo "</table>";
        ?>
    </body>
</html>

結果:

一只忙碌的貓

應該是這樣的

<?php 
    $sql = "SELECT * FROM emp ";
    $result= mysql_query($sql);
    while($row=mysql_fetch_array($result)):
      $ename = $row['ename'];

      // count the esal in each ename
      $sql2 = "SELECT * FROM emp WHERE ename=$ename";
      $result2 = mysql_query($sql2);
      $count_result2 = mysql_num_rows($result2);

    ?>
      <tr >
        <td rowspan="<?php echo $count_result2; ?>"><?php echo $row['ename']; ?></td>
        <?php
          // loop each esal
          while($row2 = mysql_fetch_array($result2)):
          ?>
              <td><?php echo $row['esal']; ?></td>
            </tr>
          <?php
          endwhile; // endwhile for each esal looping
    endwhile; // endwhile for the main looping
    ?>

像這樣的東西?

While data
 echo
   <tr>
        <td rowspan="3"><p>numbers</p></td>
        <td><p>1</p></td>
        <td><p>2</p></td>
 </tr>

請發布您的代碼

您可以使用最后一行和當前行檢查這樣的條件。

$sql = "select * from emp";
$result= mysql_query($sql);
echo "<table>";
while($row=mysql_fetch_array($result))
{ 
  $now=$row[0];
  if($last!=$now) {
  echo "<tr><td>$row['ename']</td><td>$row['esal']</td></tr>";
  }else{
  echo "<tr><td>&nbsp;</td><td>$row['esal']</td></tr>";
  }
  $last = $row[0];
 }
echo "</table>";

我希望這能幫到您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM