简体   繁体   中英

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

$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; after $fail = true; it will run faster and return the same result. There's no need to check the rest after the first failure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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