我需要在我的平面数组中对值进行分组,以便每个非整数值在我的结果数组中开始一个新的组/行,并且在下一个出现的非整数之前遇到的每个整数值都应该被插入相应的子数组中组/行。
输入:
$unitsList = [
"Aulas Gratuitas",
"149",
"151",
"153",
"Módulo 0",
"964",
"989",
"Módulo 1",
"985",
"1079",
"1001",
"1003"
"Módulo 2",
"1009"
];
当前代码:
$newArr = array();
foreach( $unitsList as $item ) {
if( !is_numeric($item) ) {
$title = array( "title" => $item, "units" => "" );
array_push( $newArr, $title);
} elseif ( is_numeric($item) ) {
$number = $item;
array_push( $newArr, $number);
}
}
当前结果:
[
[
"title" => "Aulas Gratuitas",
"units" => ""
]
"149",
"151",
"153",
[
"title" => "Módulo 0",
"units" => ""
],
"964",
"989",
[
"title" => 'Módulo 1',
"units" => ""
],
"985",
"1079",
"1001",
"1003"
[
"title" => 'Módulo 2',
"units" => ''
],
"1009"
]
如您所见,我很难将数字添加到“单位”键中。
期望的结果:
[
[
"title" => "Aulas Gratuitas",
"units" => ["149", "151", "153"]
],
[
"title" => 'Módulo 0',
"units" => ["964", "989"]
],
[
"title" => 'Módulo 1',
"units" => ["985", "1079", "1001", "1003"]
],
[
"title" => "Módulo 2",
"units" => ["1009"]
]
]
最佳答案
这样您就不需要跟踪第一级索引,在将新行插入结果数组后使用引用变量并将相关数据插入该变量。
代码:(Demo)
$result = [];
foreach ($array as $value) {
if (!ctype_digit($value)) {
unset($units);
$units = [];
$result[] = ['title' => $value, 'units' => &$units];
} else {
$units[] = $value;
}
}
var_export($result);
unset()
用于销毁对前一组的引用,否则新推送的数据将被发送到结果数组中的两个(或更多)位置。引用变量的默认值为
null
。如果您的title
值保证后跟整数/单位值,则可以删除$units = [];
。如果您有一个title
,然后是另一个title
,则前一个title
组将没有数据。使用显式数组声明,该组将有一个空的units
数组而不是null
。
使用相同的一般技术回答的相关问题:
- Group array of objects into deeper parent-child structure
- Split flat array into grouped subarrays containing values from consecutive key in the input array
- How to split a string by repeated characters in PHP?
如果您正在运行 PHP7.3 或更高版本(此时您肯定应该是)并且您对使用引用变量感到害怕/困惑,那么您可以利用 array_key_last()
来定位最新创建的数组行。
代码:(Demo)
$result = [];
foreach ($array as $value) {
if (!ctype_digit($value)) {
$result[] = ['title' => $value, 'units' => []];
} else {
$result[array_key_last($result)]['units'][] = $value;
}
}
var_export($result);
关于php - 将平面数组转换为 3d 数组,在每个非数字值上创建新的分组行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74075843/