php - 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_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”。
我忍不住想我会以一种奇怪的方式来解决这个问题。任何人都可以提出更好的解决方案吗?
背景信息:我收到的数据$data
不是我可以修改的,因为用例需要这种格式,这是应用程序中的一个功能,如下所示:jQuery load more data on scroll
解决方案
您可以使用and 来使用和foreach
分组regulations_label
groups_label
$group = [];
foreach($data as $v){
$group[$v['regulations_label']][$v['groups_label']][] = $v['filters_label'];
}
推荐阅读
- mpi - 在集群中运行 mpiexec 时出现“主机密钥验证失败”错误
- graphql - Graphiql 不显示订阅的传入数据
- openvino - 英特尔 OpenVINO 预训练模型从中优化的原始父网络的 DNN 网络架构,如果是,如何?
- sql - 获取在此时间或日期没有预订的所有表
- signalr - 集线器发送的块大于接收的块
- python - Python:如何使用熊猫数据框重新排序数据框中的日期列
- asp.net - 使用先前测试的值
- r - 用ggplot2显示点和水平线(段)的意思
- java - 如何破解 mysql jdbc 驱动程序以更改每个 sql 以在程序中执行
- javascript - 如何修改代码以便可以使用 react 和 typescript 调用 usehook?