我正在使用foreach循环在表中显示数组值。下面是我的桌子的样子。
<table>
<thead>
<th>Model</th>
<th>Trim</th>
<th>Year</th>
</thead>
<tbody>
<tr>
<td>Impreza</td>
<td>GC</td>
<td>1994</td>
</tr>
<tr>
<td>Impreza</td>
<td>GC</td>
<td>1995</td>
</tr>
<tr>
<td>Impreza</td>
<td>GC</td>
<td>1996</td>
</tr>
<tr>
<td>Impreza</td>
<td>GC-Turbo</td>
<td>1994</td>
</tr>
<tr>
<td>Impreza</td>
<td>GC-Turbo</td>
<td>1995</td>
</tr>
</tbody>
</table>
如何处理数组,从表中删除重复项或简化重复项?
数组值:
Array
(
[0] => Array
(
[0] => IMPREZA
[1] => GC
[2] => 1994
)
[1] => Array
(
[0] => IMPREZA
[1] => GC
[2] => 1995
)
[2] => Array
(
[0] => IMPREZA
[1] => GC
[2] => 1996
)
[3] => Array
(
[0] => IMPREZA
[1] => GC-TURBO
[2] => 1994
)
[4] => Array
(
[0] => IMPREZA
[1] => GC-TURBO
[2] => 1995
)
)
在表格中显示数组值
<table>
<thead></thead>
<tbody>
<?php foreach ($options as $option) : ?>
<tr>
<?php foreach ($option as $value) : ?>
<td><?= $value ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
我希望桌子是这样的:我将如何处理?请不要使用PHP。
<table>
<thead>
<th>Model</th>
<th>Trim</th>
<th>Year</th>
</thead>
<tbody>
<tr>
<td>Impreza</td>
<td>GC</td>
<td>1994-1996</td>
</tr>
<tr>
<td>Impreza</td>
<td>GC-Turbo</td>
<td>1994-1995</td>
</tr>
</tbody>
</table>
答案 0 :(得分:1)
答案 1 :(得分:1)
作为替代方案,您可以对Model
和Trim
使用复合键,并将Year
收集在一个数组中。
要获得结果,请将array_unique与min和max结合使用,并以短划线爆发,如果只有1年,则只保留一年。 / p>
例如:
$options = [
['IMPREZA', 'GC', 1994],
['IMPREZA', 'GC', 1995],
['IMPREZA', 'GC', 1996],
['IMPREZA', 'GC-TURBO', 1994],
['IMPREZA', 'GC-TURBO', 1995],
['IMPREZA', 'Test', 1998]
];
$result = [];
foreach ($options as $option) {
$compoundKey = $option[0] . "|" . $option[1];
isset($result[$compoundKey]) ? $result[$compoundKey][] = $option[2] : $result[$compoundKey] = [$option[2]];
}
foreach($result as $key => $value) {
$parts = explode('|', $key);
$parts[] = implode("-", array_unique([min($value), max($value)]));
$result[$key] = $parts;
}
结果
Array
(
[IMPREZA|GC] => Array
(
[0] => IMPREZA
[1] => GC
[2] => 1994-1996
)
[IMPREZA|GC-TURBO] => Array
(
[0] => IMPREZA
[1] => GC-TURBO
[2] => 1994-1995
)
[IMPREZA|Test] => Array
(
[0] => IMPREZA
[1] => Test
[2] => 1998
)
)
如果您想重置密钥,可以像array_values($result)
一样使用array_values