我正在使用 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>
最佳答案
作为替代方案,您可以使用Model
和Trim
的复合键,并将Year
收集到数组中。
要获取结果,请使用 array_unique与 min 结合和 max如果只有 1 年,则通过破折号进行爆炸以仅在结果中保留一年。
例如:
$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就像array_values($result)
关于php - 删除数组中的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56912964/