【问题标题】:Show array data in HTML table multidimensional array in php在php中的HTML表格多维数组中显示数组数据
【发布时间】:2018-09-01 08:04:53
【问题描述】:

我有一个这样的数组:-

$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 表格中为用户“测试”显示这些数据:-

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

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

【问题讨论】:

    标签: php html arrays


    【解决方案1】:

    您只需将foreach 循环移到&lt;tr&gt;...&lt;/tr&gt; 结构之外。这应该有效:

    <?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>
    

    【讨论】:

    • 老鼠!你秒杀我!干杯!
    【解决方案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>
    

    【讨论】:

      猜你喜欢
      • 2012-11-29
      • 2011-07-08
      • 2019-08-13
      • 2021-02-20
      • 2021-01-12
      • 2013-12-11
      • 2019-12-14
      • 2012-12-20
      相关资源
      最近更新 更多