我有这两个数组:
$pax = [
'person1',
'person2
];
$prices = [
[
'price1' => 100,
'price2' => 200,
'price3' => 300
],
[
'price1' => 100,
'price2' => 200,
'price3' => 300
]
];
我想从之前的值创建一个这样的表:
<table style="width:100%">
<tr>
<th>Description</th>
<th>person1</th>
<th>person2</th>
<th>Total</th>
</tr>
<tr>
<td>price1</td>
<td>$100</td>
<td>$100</td>
<td>$200</td>
</tr>
<tr>
<td>price2</td>
<td>$200</td>
<td>$200</td>
<td>$400</td>
</tr>
<tr>
<td>price3</td>
<td>$300</td>
<td>$300</td>
<td>$600</td>
</tr>
</table>
但我无法使用此代码:
$pax = ['person1', 'person2'];
$prices = [
[
'price1' => 100,
'price2' => 200,
'price3' => 300
],
[
'price1' => 100,
'price2' => 200,
'price3' => 300
]
];
$table = '<table width="100%"><thead><tr><th>Price Key</th>';
foreach ($pax as $person) {
$table .= "<th>$person</th>";
}
$table .= '<th>Total</th></thead><tbody>';
foreach ($pax as $idx => $person) {
$table .= '<tr>';
foreach ($prices[$idx] as $key => $value) {
$table .= "<td>$key</td>";
$table .= "<td>$value</td>";
$table .= '<td>Total</td>';
}
$table .= '<tr>';
}
$table .= '</tbody></table>';
我在这里缺少什么?
答案 0 :(得分:1)
你的第二个循环是里里外外的。每行用于不同的priceX
,但$pax
数组的每个元素都有一行。
您还需要计算总数。
if (!empty($prices)) { // So we don't try to access $prices[0] on empty array
foreach (array_keys($prices[0]) as $key) {
echo "<td>$key</td>";
$total = 0;
foreach ($prices as $person) {
$total += $person[$key];
echo "<td>\${$person[$key]}</td>";
}
echo "<td>\$$total</td>";
}
}
答案 1 :(得分:0)
你快到了。但是你的第二个for
循环中存在一些问题。
试试这个:
foreach (array_keys($prices[0]) as $key) {
echo "<td>$key</td>";
$total = 0;
foreach ($prices as $price) {
echo "<td>\${$price[$key]}</td>";
$total += $price[$key];
}
echo "<td>\$$total</td>";
}