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

发布于 2025-01-06 03:18:57 字数 854 浏览 0 评论 0原文

我正在尝试创建一个函数来循环遍历不同长度的数组。在循环期间,运行一个函数来查看前一个项目(当前键减 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;

我认为我需要一个递归函数......任何帮助或推动正确的方向将不胜感激。

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.
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). 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你爱我像她 2025-01-13 03:18:57
$prev = null;
foreach ($terms1 as $v) {
    if ($prev == getParent($v)) {
        $fail = true;
        break;
    }

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

    $prev = $v;
}
归属感 2025-01-13 03:18:57

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

I don't understand why your code doesn't work, but if you add a break; after $fail = true; it will run faster and return the same result. There's no need to check the rest after the first failure.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文