首页 > 解决方案 > 循环遍历数组递归 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']
];

有没有人有建议或答案?预先感谢

标签: phplaravel

解决方案


递归执行此操作的一种方法是:

<?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 小提琴


推荐阅读