如何在html表中获取数组输出

时间:2016-01-08 10:45:54

标签: php html html-table

我想做的是以下内容:

我有一个SQL查询,它给了我一个输出。在输出1上进行选择。

$cities[$row['stad']][$row['status']]++

这给了我这样的输出(在<pre>标签内):

Array
(
    [Amsterdam] => Array
        (
            [41] => 2
            [21] => 91
            [43] => 16
            [42] => 2
            [20] => 30
            [4] => 4
            [70] => 3
            [84] => 8
            [46] => 4
            [45] => 5
            [999] => 26
            [47] => 2
            [3] => 8
            [44] => 1
            [40] => 1
            [93] => 5
            [56] => 3
            [61] => 3
            [79] => 3
            [48] => 2
            [50] => 5
            [10] => 10
            [52] => 2
            [120] => 1
            [95] => 1
            [1] => 65
            [90] => 6
        )

我想像这样放入一个html表:

City        41  21  43  42  20  7   …… etc 
amsterdam   2   91  16  2   30  4   …… etc 

重要的是要知道有超过1个城市。

这就是我现在所拥有的:

echo '<table cellpadding="10" cellspacing="10" border="1">';

foreach($cities as $city) { 
    echo '<tr>';
    echo '<td>' . $row['stad'] . '</td>';
    echo '<td>' . $city[$row['status']] . '</td>';

    echo '</tr>';
}

echo '</table>';

4 个答案:

答案 0 :(得分:1)

您需要另一个列出所有标题值的数组;在下面的代码中,我将此数组称为$headings。这是因为每个城市的值可能按其不同的顺序排列,并且可能缺少按键,因此只需循环遍历城市数组就不会在每一行上获得一致的值。

$headings = array(41, 21,  43,  42,  20,  7, etc.); 

echo '<table cellpadding="10" cellspacing="10" border="1">';
echo '<tr><th>City</th>';
foreach ($headings as $h) {
    echo "<th>$h</th>";
}
echo '</tr>';

foreach($cities as $cityname => $city) { 
    echo '<tr>';
    echo "<td>$cityname</td>";
    foreach ($headings as $h) {
        echo '<td>' . (isset($city[$h]) ? $city[$h] : '') . '</td>';
    }    
    echo '</tr>';
}

echo '</table>';

答案 1 :(得分:0)

只需在数组上使用foreach即可构建表格。

<table>
    <tbody>
        <?php foreach ($cities as $key => $value): ?>
        <tr>
            <td><?= $key; ?>
            <?php foreach ($value as $subkey => $subvalue): ?>
                <td><?= $subvalue; ?> </td>
            <?php endforeach; ?>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

分步骤:

  • 遍布所有城市
  • 由于每个城市都有自己的子数组,我们将遍历该数组

答案 2 :(得分:0)

将foreach与$ key元素一起使用,以便直接获取密钥

更改此代码

foreach($cities as $city) { 
    echo '<tr>';
    echo '<td>' . $row['stad'] . '</td>';
    echo '<td>' . $city[$row['status']] . '</td>';

    echo '</tr>';
}

foreach($cities as $key=> $city) { 
    echo '<tr>';
    echo '<td>' . $key. '</td>';
    echo '<td>' . $city . '</td>';

    echo '</tr>';
}

答案 3 :(得分:0)

试试这个 -

<?php
echo '<table cellpadding="10" cellspacing="10" border="1">';
foreach($cities as $city):
foreach($city as $k => $v)
{
echo "<tr><td>$k</td><td>$v</td></tr>";
}
endforeach;
?>