Php 删除数组中的重复值
我使用foreach循环在表中显示数组值。下面是我的桌子的样子Php 删除数组中的重复值,php,arrays,foreach,Php,Arrays,Foreach,我使用foreach循环在表中显示数组值。下面是我的桌子的样子 <table> <thead> <th>Model</th> <th>Trim</th> <th>Year</th> </thead> <tbody> <tr> <td>Impreza</td&g
<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>
在表中显示数组值
<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>
模型
修剪
年
翼豹
GC
1994-1996
翼豹
GC涡轮增压器
1994-1995
我的方法看起来有点长,但这个数组结果肯定会帮助您轻松构建表
$result = $expected_array = [];
foreach($array as $k=>$v){
$result[$v[0].'#'.$v[1]][] = $v[2]; //making unique key value with # for year
}
foreach($result as $key=>$value){
list($model,$trim) = explode('#',$key); // exploding with # to get model and trim
$expected_array[]= ['Model'=>$model, 'Trim'=>$trim,'Year'=>implode('-',[$value[0],$value[count($value)-1]])];
}
print_r($expected_array);
工作演示:作为一种替代方法,您可以对
型号和修剪使用复合键,并在数组中收集年份
要获得结果,请将a与and结合使用,并用破折号爆炸,如果结果只有一年,则只保留一年
例如:
$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
)
)
如果要重置键,可以使用likearray\u values($result)
数组中有表值还是只有静态值?是的。我已经编辑了我的问题,将其包括在内。请check@SamN这是来自数据库吗?如果是,则显示SQL查询和表结构。
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
)
)