如何从匹配并保留的数组中获取所有值

Reference of my Question

how can I get the closest pairs from this array

// Input
$required = 1.3;
$array_result = [0.6, 0.5, 0.8, 0.7];

// Algorithm
$remaining = $required;
$whichtakes = [];
foreach($array_result as $i => $a) {
    foreach(array_slice($array_result, $i+1) as $b) {
        $test = $required - $a - $b;
        if ($test >= 0 and $test < $remaining) {
            $remaining = $test;
            $whichtakes = [$a, $b];
        }
    }
}

// Output
print_r($whichtakes);   // [0.5, 0.8]
print_r($remaining);    // 0

Thanks to trincot

its working fine with pairs but there is little change , Algorithm is getting pairs but i want array which match my result array, just need this little change. if $required = 1.3 change to $required = 1.8 now it should give me array 0.6,0.5,0.7 and if $required = 1.9 now it should give me array 0.6,0.5,0.7 and 0.1 remaining

This algorithm is part of dynamic programming. Here is the modified code.

$res = array();
function isSubsetSum($set, $n, $sum)
{
    if ($sum == 0)
        return true;
    if ($n == count($set) - 1 && $sum != 0)
        return false;

    if ($set[$n + 1] > $sum) {
        return isSubsetSum($set, $n + 1, $sum);
    }

    return isSubsetSum($set, $n + 1, $sum) || 
        isSubsetSum($set, $n + 1, $sum - $set[$n + 1]);
}

$set = array(0.6, 0.5, 0.8, 0.7);
$sum = 1.8;
$n = 0;
$remaining = 0;

while (!isSubsetSum($set, 0, $sum)) {
    $remaining += 0.1;
    $sum -= 0.1;
}
echo $res; // the array result
echo $remaining;

This code doesn't store the array subset. You can store the array result inside the function. I don't know how to optimize this algorithm though.

For more information about dynamic programming, check this link