dpsu84620 2014-08-06 02:19
浏览 78
已采纳

显示偶数和奇数SQL结果(PHP)

I have a PHP while loop that pulls from an SQL database and displays the contents in a table with two columns.

// Check Connection
    if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

// Select Data Table
    $result = mysqli_query($con,"SELECT * FROM Recommendations") or die(mysqli_error);

// Split Data
    $mid = ceil(mysqli_num_rows($result)/2);

// Display Content
    while ($rows = mysqli_fetch_array($result)) {
        $Name = $rows['Name'];
        $Author = $rows['Author'];
        $Cover = $rows['Link to Cover'];
        $Link = $rows['Link to Profile'];
    echo "<table><tr><td>
    <a href='" . $Link . "' >".$Name."</a>
    <br />".
    $Author.
    "<br />
    <a href='" . $Link . "' ><img src='" . $Cover . "' /></a>
    </td>
    <td>
    <a href='" . $Link . "' >".$Name."</a>
    <br />".
    $Author.
    "<br />
    <a href='" . $Link . "' ><img src='" . $Cover . "' /></a>
    </td></tr></table>";
    }
?>

I want to be able to display the looped results side by side in columns of two.

ex. 1 2
    3 4
    5 6

I've tried using pseudo classes to display only the even and odd results in the different table columns, but honestly have no idea how to do this. I'm new to PHP, so my apologies if the results are really obvious. Thanks in advance!

  • 写回答

2条回答 默认 最新

  • drduinfu915094 2014-08-06 02:40
    关注

    I'll show you a simple option to split the even and odd numbers.

    foreach($numbers as $n) {
        ($n % 2 == 0) ? array_push($e, $n): array_push($o, $n);
    }
    

    The above is a short-hand ternary operator (?:)

    The above function will check if the the number is even or odd. It stores the even/odd values in their own seperate arrays, which in this case is $e for even and $o for odd.

    If you want to see how it works, Check this Example Out.


    Using the above example, you'd do something like this (AS PSEUDO CODE)

    WHILE(ROW = MYSQL.FETCH(DATA)) {
        MYDATA[] = ROW;
    }
    
    // now we do presentation
    FOREACH(MYDATA AS ITEM) {
        IF(ITEM.NUMBER % 2 == 0) {
            PRINT EVEN.INFORMATION;       
        } ELSE {
            PRINT ODD.INFORMATION;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路