简体   繁体   English

PHP 递归数组搜索

[英]PHP recursive array_search

From the code below I can compare the 2 arrays and find out the $subset elements position range in $array .从下面的代码中,我可以比较 2 arrays 并找出$array中的$subset元素 position 范围。

$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:但是,我想对我的多维数组进行递归array_search ,例如:

$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] .预期结果 -> [2, 5], [1, 8], [2, 6]

You do not need a recursion here, simply add an additional loop in the get_range() function.这里不需要递归,只需在get_range() function 中添加一个额外的loop 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 ) 
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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