简体   繁体   English

如何遍历不同长度的数组并在循环内运行函数

[英]How to loop through arrays of different lengths and run a function inside the loop

I'm trying to create a function that will loop through an array of various lengths. 我正在尝试创建一个将遍历各种长度的数组的函数。 During the loop, a function is run to see if the immediately prior item (the item at current key minus 1) matches what is in the array. 在循环期间,将运行一个函数,以查看紧接的前一项(当前键为1的项)是否与数组中的项匹配。 Here are two examples of arrays: 这是数组的两个示例:

$terms1 = array(
    0 => 'MEL',
    1 => 'Appliances',
    2 => 'Clothes Dryers',
    3 => 'Clothes dryers - electric'
);

$terms2 = array(
    0 => 'Clothes Dryers',
    1 => 'Clothes dryers - electric'
);

And here is the function to be run within the loop... this function will return a value and then I will compare that to what is in the array in the immediately prior location (current key minus 1). 这是要在循环中运行的函数...该函数将返回一个值,然后将其与紧邻的先前位置(当前键减1)中的数组中的值进行比较。 This pulls from a db. 这是从数据库中提取的。

getParent($terms1[3]); //Would output the value I want to compare to $terms1[2]

I've tried something like this: 我已经尝试过这样的事情:

$fail = null;
foreach(array_reverse($terms1, true) as $key => $value){
    if($key > 0){
        $priorkey = $key - 1;
        if(getParent($terms1[$key]) != $terms1[$priorkey]){
            $fail = true;
        }
    }
}
return $fail;

I think I need a recursive function... any help or nudges in the right direction would be appreciated. 我认为我需要一个递归函数...朝着正确方向的任何帮助或推动都会受到赞赏。

$prev = null;
foreach ($terms1 as $v) {
    if ($prev == getParent($v)) {
        $fail = true;
        break;
    }

    $prev = $v;
}

I don't understand why your code doesn't work, but if you add a break; 我不明白为什么您的代码无法正常工作,但是如果您添加了一个break; after $fail = true; $fail = true; it will run faster and return the same result. 它将运行得更快,并返回相同的结果。 There's no need to check the rest after the first failure. 第一次失败后,无需检查其余部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM