简体   繁体   English

在PHP中以替代行颜色打印表中的输出

[英]Printing output in Table with alternate row colors in PHP

So my code is below.The for loop is concatenating the elements from 2 arrays and printing them in a table. 所以我的代码在下面。for循环是连接2个数组中的元素并将它们打印在表中。

I have 2 questions: 我有两个问题:

1) Although the output is correct I would like to print the output by calling the first function (fullname) in the second function (printTable). 1)尽管输出正确,但我想通过在第二个函数(printTable)中调用第一个函数(全名)来打印输出。 2) I would like to print the output that is in the table rows in alternate colors of red and green. 2)我想用红色和绿色的交替颜色打印表格行中的输出。

<?php

$firstname=
array("Raj","Swati","Kunal","Hema","Kareena","Deepika","Shilpa","Amitabh","Shahrukh","Kangana"); 

$lastname=
array("Kumar","Sharma","Kapoor","Malini","Kapoor","Padukone","Shetty","Amitabh","Shahrukh","Kangana");


function fullname($fname,$lname){

for ($i=0; $i <10; $i++) {
    $wholename[]=$fname[$i]." ".$lname[$i];
}
return $wholename;
}

function printTable($firstname,$lastname){

echo"<table border='1'>";
for($i=0;$i<10;$i++){
echo"<tr><td>".$firstname[i]." ".$lastname[i]."</td></tr>";
}
echo "</table>";
}
printTable($firstname,$lastname);
?>

Something like this: 像这样:

<?php
    $firstname=
    array("Raj","Swati","Kunal","Hema","Kareena","Deepika","Shilpa","Amitabh","Shahrukh","Kangana"); 

    $lastname=
    array("Kumar","Sharma","Kapoor","Malini","Kapoor","Padukone","Shetty","Amitabh","Shahrukh","Kangana");


    function fullname($index){
        return $firstname[$index] . " " . $lastname[$index];
    }

    function printTable(){
        echo"<table border='1'>";
        for($i=0;$i<10;$i++){
            echo"<tr><td>".fullname($i)."</td></tr>";
        }
        echo "</table>";
    }
    printTable();
?>

For the row colouring see: http://www.w3.org/Style/Examples/007/evenodd 有关行着色,请参见: http : //www.w3.org/Style/Examples/007/evenodd

If you don't want to use CSS for alternating row colours, you can use the remainder/mod operator % on the loop variable. 如果您不想使用CSS来替换行颜色,则可以在loop变量上使用剩下的/ mod运算符% $i % 2 means the remainder when $i is divided by 2 (ie, alternating 0,1,0,1,... as $i is incremented). $i % 2表示$i除以2时的余数(即,随着$i递增,交替0,1,0,1,...)。

if (($i % 2) == 0) {echo "<tr bgcolor=#ff0000>"} else {echo "<tr bgcolor=#00ff00>"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM