通过简化阵列可能是持平或多维循环 [英] Simplify looping through an array which could be flat or multidimensional

查看:102
本文介绍了通过简化阵列可能是持平或多维循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常情况下,我将有一个数组持有的一组值每一个我需要处理的。有时,阵列将只持有一组,在这种情况下,每个值需要通过流程付诸表决。其他时间,该阵列将持有多套,在这种情况下,每个值将是一个数组,并且这些阵列的每个值将需要被处理。下面是一个例子:

Often, I will have an array holding a set of values each of which I need to process. Sometimes, the array will only hold a single set, in which case each value needs to be put through the process. Other times, the array will hold many sets, in which case each value will be an array and each value of those arrays will need to be processed. Here is an example:

foreach($array as $key => $value) {
    if(is_array($value)) {
        foreach($value as $subkey => $subvalue) {
            //Process $subvalue here    
        }
    }
    else {
        //Process $value here
    }
}

的问题是,在code表示处理$值/ $子值是除了它在不同的可变操作相同。简化的方法之一将是把那个code到一个功能,但它似乎仍然不雅不得不两次调用它。此外,这将使相当多的code(在foreach循环和阵列测试)的该函数之外。例如,假设过程验证,我不希望有写两个foreach循环和数组的测试每当我想打电话给我的验证功能。

The problem is that the code for processing $value/$subvalue is identical except that it operates on a different variable. One way to simplify this would be to put that code into a function but it still seems inelegant to have to call it twice. Furthermore, that would leave quite a lot of code (the foreach loops and array test) outside of that function. For example, say the process is validation, I don't want to have to write two foreach loops and an array test whenever I want to call my validation function.

是否有这样做的一个简单的方法?

Is there a simpler way of doing this?

推荐答案

裹单值到一个数组,然后继续像往常一样:

Wrap the single value into an array, then proceed as usual:

foreach($array as $key => $value) {

    if(!is_array($value)) $value = array($value);

    foreach($value as $subkey => $subvalue) {
        //Process $value/$subvalue here    
    }
}

另外,您可以创建处理单品的处理函数,然后调用每个分支相同的功能。您还是挽救了写作过程中的两倍。

Alternatively you can create a function that handles the processing of single items, then call that same function from each branch. You'll still end up saving writing the process twice.

这篇关于通过简化阵列可能是持平或多维循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆