Php 将数组中的值之和与数字匹配
我想用一个特定的数字来匹配数组中不同的值组合 För示例:Php 将数组中的值之和与数字匹配,php,Php,我想用一个特定的数字来匹配数组中不同的值组合 För示例: number = 10 Array (2, 6, 5, 3, 4) 匹配将返回:6+4=10,2+3+5=10 我可以循环使用所有可能的组合,但有没有更快或更简单的方法来解决我的问题?答案有一个小问题,它返回所有组合,即2,3,5和3,2,5等 没有内置函数来执行此操作,因此需要循环。。。。减少循环的唯一方法是从数组中筛选出大于目标数的任何值,尽管这不适用于您的示例案例谢谢!然后,我将尝试通过删除不必要的值来优化数组。 <?p
number = 10
Array (2, 6, 5, 3, 4)
匹配将返回:6+4=10,2+3+5=10
我可以循环使用所有可能的组合,但有没有更快或更简单的方法来解决我的问题?答案有一个小问题,它返回所有组合,即2,3,5和3,2,5等
没有内置函数来执行此操作,因此需要循环。。。。减少循环的唯一方法是从数组中筛选出大于目标数的任何值,尽管这不适用于您的示例案例谢谢!然后,我将尝试通过删除不必要的值来优化数组。
<?php
$array = array(2, 6, 5, 3, 4);
function depth_picker($arr, $temp_string, &$collect) {
if ($temp_string != "")
$collect []= $temp_string;
for ($i=0; $i<sizeof($arr);$i++) {
$arrcopy = $arr;
$elem = array_splice($arrcopy, $i, 1); // removes and returns the i'th element
if (sizeof($arrcopy) > 0) {
depth_picker($arrcopy, $temp_string ."," . $elem[0], $collect);
} else {
$collect []= $temp_string. "," . $elem[0];
}
}
}
$collect = array();
depth_picker($array, "", $collect);
foreach($collect as $val)
{
$sum = array_sum(explode(",",$val));
if($sum == 10){
print_r($val);
echo "<br>";
}
}
?>