首页 > 解决方案 > PHP - 只有在迭代之间发生变化时才循环遍历数组并打印出值

问题描述

抱歉,如果有人问过这个问题,但我找不到满足我需求的解决方案。

我在 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_labelgroups_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”。

我忍不住想我会以一种奇怪的方式来解决这个问题。任何人都可以提出更好的解决方案吗?

背景信息:我收到的数据$data不是我可以修改的,因为用例需要这种格式,这是应用程序中的一个功能,如下所示:jQuery load more data on scroll

标签: phparrays

解决方案


您可以使用and 来使用和foreach分组regulations_labelgroups_label

$group = [];
foreach($data as $v){
  $group[$v['regulations_label']][$v['groups_label']][] = $v['filters_label'];
}

演示


推荐阅读