【问题标题】:How could I loop through an arbitrary amount of sub-arrays?我怎样才能遍历任意数量的子数组?
【发布时间】:2014-01-09 21:37:56
【问题描述】:

例如:

$array = [
    [
        'Item 1',
        'Item 2',
        [
            'Item 3',
            [
                'Item 4'
            ]
        ],
        'Item 5',
        [
            'Item 6'
        ]
    ]
];

什么是最好的方法,例如,循环遍历数组中的每个项目,包括子数组,并回显它们,产生Item 1Item 2Item 3Item 4Item 5

我知道我在 foreach 中包含一个 foreach...但是我这样做的原因是因为我希望能够存储理论上无限数量的子类别,而不是限制不管我有多少 foreaches。

【问题讨论】:

  • 递归是程序员的朋友。
  • 递归是程序员朋友朋友朋友朋友... :-)\

标签: php loops foreach arrays


【解决方案1】:

这最好由递归函数而不是直接循环来处理。例如:

    function printArray($arr){
        foreach($arr as $val){
            if(is_array($val)){
               printArray($val);
            }
            else{
               echo $val;
            }
        }
    }

【讨论】:

    【解决方案2】:
    function items($arr)
    {
        foreach($arr as $value)
        {
            if(!is_array($value)) echo $value."\n";
            if(is_array($value)) items($value);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-13
      • 1970-01-01
      • 2019-11-17
      • 2022-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多