php - 循环遍历数组递归 PHP
问题描述
我想创建一个函数以递归方式循环遍历简单数组
$values = [
'sizes' => ['S', 'M', 'L', 'XL'],
'colors' => ['Red', 'Blue', 'Green'],
'types' => ['Short', 'Long'],
];
要得到这个结果:
foreach($sizes as $size){
foreach($colors as $color){
foreach($types as $type){
$str = "$size $color $type";
// S Red Short
// S Red Long
// S Blue Short
// ...
// M Red Long
// M Blue Short
// M Blue Long
// ...
// XL Blue Long
// XL Green Short
// XL Green Long
}
}
}
我的数组是完全可变的,我可以拥有:
$values = [
'sizes' => ['S', 'M'],
'colors' => ['Red', 'Blue', 'Green', 'White', 'Black'],
];
或者
$values = [
'sizes' => ['S', 'M', 'L'],
'colors' => ['Red', 'Blue'],
'type' => ['short']
];
有没有人有建议或答案?预先感谢
解决方案
递归执行此操作的一种方法是:
<?php
$properties = [
'sizes' => ['S', 'M', 'L', 'XL'],
'colors' => ['Red', 'Blue', 'Green'],
'types' => ['Short', 'Long'],
];
function recurseProperties($properties, $output = '')
{
// are there still values left in the properties array?
if (count($properties) > 0) {
// pick off first array from the properties
$values = array_shift($properties);
// do all values recursively
foreach ($values as $value) {
recurseProperties($properties, "$output $value");
}
} else {
// output what we have so far
echo trim($output) . PHP_EOL;
}
}
recurseProperties($properties);
该代码是不言自明的。我在代码中添加了一些注释。输出是:
S Red Short
S Red Long
S Blue Short
S Blue Long
S Green Short
S Green Long
M Red Short
M Red Long
M Blue Short
M Blue Long
M Green Short
M Green Long
L Red Short
L Red Long
L Blue Short
L Blue Long
L Green Short
L Green Long
XL Red Short
XL Red Long
XL Blue Short
XL Blue Long
XL Green Short
XL Green Long
这是一个PHP 小提琴。
推荐阅读
- r - Scheffe Test in R
- ssrs-2012 - SSRS:导出到 Excel 后将名称添加到工作表
- ms-access - 操作方法:在由键组织的字段中包含串联文本的报告
- ruby-on-rails - Rails i18n 如何获取语言环境文件的所有键?
- r - 使用 data.table 删除部分字符串
- javascript - 如何转换值表以将其集成到 http.get
- pyspark - Spark Structured Streaming - 无法解析“Kafka”格式(Cloudera 集群上的 Jupyter notebook)
- ansible - 如何在此任务中使用“列表”变量
- loops - 从过滤的数据中循环遍历每一行
- awk - 如何在最后一场比赛后打印第 6 行到第 10 行?