在PHP中的HTML表多维数组中显示数组数据

时间:2018-09-01 08:04:53

标签: php html arrays

我有一个像这样的数组:-

$str = array(
    array(
        'amount' => 1.87,
        'user' => 'hello',
    ),
    array(
        'amount' => 0.9,
        'user' => 'test',
    ),
    array(
        'amount' => 9,
        'user' => 'hello',
    ),
    array(
        'amount' => 1.4,
        'user' => 'test',
    )
);

现在,我在HTML表中为用户“ test”显示此数据:-

<thead>
    <tr>
        <th>Amount</th>
        <th>User</th>
</thead>
<tbody>
    <tr>
        <td><?php
            foreach ($str as $new_str) {
                if ($new_str['user'] == "test") {
                    echo $new_str['amount'];
                    echo "<br />";
                }
            }

            ?></td><td><?php
            foreach ($str as $new_str) {
                if ($new_str['user'] == "test") {
                    echo $new_str['user'];
                    echo "<br />";
                }
            }
            ?></td>
    </tr>
</tbody>

但是现在的问题是,当我使用此代码时,它显示的是整个用户的数量和用户,而不是两个不同的行。我怎样才能解决这个问题?有帮助吗?

2 个答案:

答案 0 :(得分:3)

您只需要将foreach循环移到<tr>...</tr>结构之外。这应该起作用:

<?php foreach($str as $new_str){
    if($new_str['user']=="test"){
        echo "<tr><td>" . $new_str['amount'] . "</td><td>" . $new_str['user'] . "</td></tr>";
    }
}
?>

输出(用于您的数据)

<tr><td>0.9</td><td>test</td></tr>
<tr><td>1.4</td><td>test</td></tr>

答案 1 :(得分:2)

您的tr不在重复。 output image我希望这会有所帮助。

    <?php
       $str = array(
            array(
                'amount' => 1.87,
                'user' => 'hello',
            ),
            array(
                'amount' => 0.9,
                'user' => 'test' ,
            ),
            array(
                'amount' => 9,
                'user' => 'hello',
            ),
            array(
                'amount' => 1.4,
                'user' => 'test',
            )
);
?>
<table>
    <thead>
            <tr>
                <th>Amount</th>
                <th>User</th>
            </tr>
    </thead>
    <tbody>
                <?php foreach($str as $new_str) {
                    if($new_str['user'] == "test"){
                        echo '<tr>';
                        echo '<td>'.$new_str['amount'].'</td>';
                        echo '<td>'.$new_str['user'].'</td>';
                        echo '</tr>';
                    }
                } ?>

    </tbody>
</table>
相关问题