我尝试以递归方式查找数组与另一个数组的匹配但代码失败并在匹配找不到时抛出错误。这是我的完整代码,只有在找到匹配项时才有效,否则递归函数不能用于查找其他匹配项。
<?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
如何修复它以使用递归函数找到其他匹配?
答案 0 :(得分:1)
您可以使用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];
}