简体   繁体   中英

PHP recursive array_search

From the code below I can compare the 2 arrays and find out the $subset elements position range in $array .

$array = [8,2,3,7,4,6,5,1,9];
$subset = [6,3,7];

function get_range($array, $subset)
{
    $min = sizeof($array);
    $max = 0;
    
    foreach($subset as $value) {
        $occurrence = array_search($value, $array);
        if( $occurrence < $min ) {
            $min = $occurrence;
        }
        if( $occurrence >  $max ) {
            $max = $occurrence;
        }
    }
    
    return [$min, $max];
}
$range = get_range($array, $subset);  // result as an array -> [2, 5]

However, I want to do a recursive array_search for my multidimentional array like:

$subset =  array (
  array(6,3,7),
  array(4,2,9),
  array(3,5,6),
);

How can I do this? Expecting results -> [2, 5], [1, 8], [2, 6] .

You do not need a recursion here, simply add an additional loop in the get_range() function. The following example is based on your code and is a possible solution to your problem:

<?php
$array = [8,2,3,7,4,6,5,1,9];
$subsets =  array (
  array(6,3,7),
  array(4,2,9),
  array(3,5,6),
);

function get_range($array, $subsets)
{
    $result = array();
    foreach ($subsets as $subset) {
        $min = sizeof($array);
        $max = 0;
        foreach($subset as $value) {
            $occurrence = array_search($value, $array);
            if( $occurrence < $min ) {
                $min = $occurrence;
            }
            if( $occurrence >  $max ) {
                $max = $occurrence;
            }
        }
        $result[] = [$min, $max];
    }
    
    return $result;
}

$range = get_range($array, $subsets);
echo print_r($range, true);
?>

Result:

Array ( 
    [0] => Array ( [0] => 2 [1] => 5 ) 
    [1] => Array ( [0] => 1 [1] => 8 ) 
    [2] => Array ( [0] => 2 [1] => 6 ) 
)

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