用PHP遍历多维数组似乎跳过了值

时间:2019-02-18 17:29:59

标签: php arrays

我是PHP的新手,仅将其用于类,并且尝试遍历多维数组。由于某种原因,我正在使用的foreach似乎跳过了数组中的所有其他位置。

这是我要遍历的数组:

define('TAX_RATES',
    array(
        'Single' => array(
            'Rates' => array(10, 15, 25, 28, 33, 35, 39.6),
            'Ranges' => array(0, 9275, 37650, 91150, 190150, 413350, 415050),
            'MinTax' => array(0, 927.5, 5183.75, 188588.75, 46278.75, 119934.75, 120529.75)
        ),
        'Married_Jointly' => array(
            'Rates' => array(10, 15, 25, 28, 33, 35, 39.6),
            'Ranges' => array(0, 18550, 75300, 151900, 231450, 413350, 466950),
            'MinTax' => array(0, 1855, 10367.5, 29517.5, 51791.5, 111818.5, 130578.5)
        ),
        'Married_Separately' => array(
            'Rates' => array(10, 15, 25, 28, 33, 35, 39.6),
            'Ranges' => array(0, 9275, 37650, 75950, 115725, 206675, 233475),
            'MinTax' => array(0, 927.5, 5183.75, 14758.75, 25895.75, 55909.25, 65289.25)
        ),
        'Head_Household' => array(
            'Rates' => array(10, 15, 25, 28, 33, 35, 39.6),
            'Ranges' => array(0, 13250, 50400, 130150, 210800, 413350, 441000),
            'MinTax' => array(0, 1325, 6897.5, 26835, 49417, 116258.5, 125936)
        )
    )
);

这是我遍历数组的方式:

echo '
<div class="container">
    <h2>2016 Tax Tables</h2>';
foreach (TAX_RATES as $status => $inner) {
    echo '<h4>'.$status.'</h4>'.'
<table class="table table-striped>
    <thead>
        <tr>
            <th>Taxable Income<th>
            <th>Tax Rate<th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>'.money_format('%10n', $inner['Ranges'][0]).' - '.money_format('%10n', $inner['Ranges'][1]).'</td>
            <td>'.$inner['Rates'][0].'%'.'</td>
        </tr>
    </tbody>
</table>';
}
echo '
</div>';

这是我得到的输出: enter image description here

看看它如何跳过Married_Jointly和Head_Household吗?

这是我试图产生的: enter image description here

有人可以告诉我我做错了什么吗?我知道我无法完成所有表条目的构建。

如果我摆脱了表格,似乎可以遍历所有申请状态:

echo '
<div class="container">
    <h2>2016 Tax Tables</h2>';
foreach (TAX_RATES as $status => $inner) {
    echo '<h4>'.$status.'</h4>';
}

enter image description here

我真的不知所措。

1 个答案:

答案 0 :(得分:3)

您的循环是正确的。最终的HTML标记被破坏,导致元素出现在源代码中,但在输出中在视觉上被忽略:

<table class="table table-striped>

应该是:

<table class="table table-striped">

缺少右引号。