将数组转换为HTML表,空单元格为缺失值

时间:2016-01-01 17:49:19

标签: php arrays

我有一个带数值的数组。每个值都不同,数组按升序排序,从最小1到最大80。

$numbers = array( "1", "3", "5", "6", "12", "13", "15", "20",
                  "24", "28", "32", "33", "34", "42", "47",
                  "49", "50", "54", "59", "79");

我想在一个表行中显示这个数组,每个数字在一个单元格中,非现有值显示为空单元格,如下所示:

<tr>
    <td>1<td>
    <td><td>
    <td>3<td>
    <td><td>
    <td>5<td>
    <td>6<td>
    ....

换句话说,如果数组中缺少值,则应插入空表单元格。在上面的示例中,24所在的单元格为空,因为这些值不在数组中。

总共会有80 <td>

2 个答案:

答案 0 :(得分:6)

这样的事情(假设最小值为1,最大值为80):

echo '<tr>';
for ($i = 1; $i <= 80; $i++) {
    echo '<td>';
    echo ( in_array( $i, $numbers ) ) ? $i : '';
    echo '</td>';
}
echo '</tr>';

如果要动态查找数组的最小值/最大值:

$min = min( $numbers );
$max = max( $numbers );

echo '<tr>';
for ($i = $min; $i <= $max; $i++) {
    echo '<td>';
    echo ( in_array( $i, $numbers ) ) ? $i : '';
    echo '</td>';
}
echo '</tr>';

答案 1 :(得分:0)

解决了这样的问题:

$numbers=array("1","6","7","10","12","16","17","22","27","34","35","45","49","52","53","56","57","76","78","80");

function results($array){
    echo "<tr>";
    for ($i=1; $i<81 ; $i++) { 
        if (in_array($i, $array)) {
            echo "<td>".$i."</td>";
        }
        else{
            echo "<td></td>";
        }
    }
    echo "</tr>";
}

results($numbers);