如何在不同长度的数组中循环,并在循环中运行函数


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

我正在尝试创建一个函数,该函数将循环通过不同长度的数组。在循环过程中,将运行一个函数来查看紧挨在前面的项(当前键减1的项)是否与数组中的项匹配。以下是两个阵列示例:

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

这是要在循环中运行的函数。。。这个函数将返回一个值,然后我将其与数组中紧接在前一个位置的值(当前键减1)进行比较。这是从数据库中提取的。

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

我试过这样的东西:

$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;

我想我需要一个递归函数。。。如有任何帮助或推动,我们将不胜感激。

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

我不明白为什么您的代码不起作用,但如果在$fail = true;之后添加break;,它会运行得更快,并返回相同的结果。在第一次失败后,没有必要检查其余部分。