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条)

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊