如果有人问过这个问题,但我找不到满足我需求的解决方案,我深表歉意。
我在 PHP 7 应用程序中有一个数组,如下所示:
$data = [
0 => [
'regulations_label' => 'Europe',
'groups_label' => 'G1',
'filters_label' => 'FF1'
],
1 => [
'regulations_label' => 'Europe',
'groups_label' => 'G1',
'filters_label' => 'FF900'
],
2 => [
'regulations_label' => 'Europe',
'groups_label' => 'G1',
'filters_label' => 'FF324234'
],
3 => [
'regulations_label' => 'Europe',
'groups_label' => 'G2',
'filters_label' => 'FF23942'
],
4 => [
'regulations_label' => 'America',
'groups_label' => 'G29',
'filters_label' => 'FF3242'
],
5 => [
'regulations_label' => 'America',
'groups_label' => 'G29',
'filters_label' => 'FF78978'
],
6 => [
'regulations_label' => 'America',
'groups_label' => 'G29',
'filters_label' => 'FF48395043'
],
7 => [
'regulations_label' => 'Asia',
'groups_label' => 'G2000',
'filters_label' => 'FF7'
],
// ...
];
我想要实现的输出是这样的:
Europe
- G1
-- FF1
-- FF900
- G2
-- FF23942
America
- G29
-- FF3242
-- FF48395043
Asia
- G2000
-- FF7
本质上,它所做的就是以结构化格式输出数组,以便它显示regulations_label后跟任何对应的groups_label,然后是任何filters_label。
遍历整个数组很简单,例如
foreach ($data as $d) {
echo $d['regulations_label'] . "\n";
echo ' - ' . $d['groups_label'] . "\n";
echo ' -- ' . $d['filters_label'] . "\n";
}
然而,这引入了“重复”标题regulations_label,groups_label因为它正在打印每个键。但是我不知道如何检查这在foreach语句期间是否已更改,因为$d它始终是当前元素。
我试图根据以前的数组键进行检查:
foreach ($data as $key => $d) {
if ($data[$key-1]['regulations_label'] !== $d['regulations_label']) {
echo $d['regulations_label'] . "\n";
echo "-" . $d['groups_label'] . "\n";
}
}
麻烦的是,这然后只打印 1groups_label所以我最终会得到 - 例如:
Europe
- G1
America
...
它不会达到“G2”。
我不禁觉得我在用一种奇怪的方式来处理这个问题。谁能建议一个更好的解决方案?
千巷猫影
慕桂英4014372