如何循环不同长度的数组并在循环内运行函数
我正在尝试创建一个函数来循环遍历不同长度的数组。在循环期间,运行一个函数来查看前一个项目(当前键减 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不明白为什么你的代码不起作用,但如果你在
$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.