我试图递归地查找一个数组与另一个数组的匹配项,但如果没有找到匹配项,代码将失败并抛出错误。这是我的完整代码,它只在找到匹配时才起作用,否则递归函数就不能找到另一个匹配。
<?php
$products = array(
191 => array(2),
192 => array(2,1),
237 => array(2,3),
238 => array(2,3,1),
239 => array(1,2),
266 => array()
);
$options = array(1,2,3);
sort($options);
echo find_product($options, $products);
function find_product($options, $products)
{
foreach($products as $key => $value)
{
sort($value);
if($value == $options)
{
$product_id = $key;
break;
}
}
if(!isset($product_id))
{
array_pop($options);
echo "<pre>";
print_r($options);
//print_r($products);
echo "</pre>";
find_product($options, $products);
}
return $product_id;
}
?>输出是238,但是当我注释数组元素时
//238 => array(2,3,1),我收到以下错误
Notice: Undefined variable: product_id in C:\wamp\www\test.php on line 37预期输出应为
239
我如何修复它,以使用递归函数来查找其他匹配项?
发布于 2018-06-07 03:04:32
你可以使用array_intersect()来简化这件事,你只需要在你的$options数组中添加一个嵌套层:
<?php
$products = array(
191 => array(2),
192 => array(2,1),
237 => array(2,3),
238 => array(2,3,1),
239 => array(1,2),
266 => array()
);
$options = array(1,2,3);
sort($options);
$resultArr = array_intersect(array($options), $products);
// this last part assigns the value that you were previously returning
if (count($resultArr) == 1) {
$yourKey = array_keys($resultArr)[0];
}https://stackoverflow.com/questions/50727103
复制相似问题