从其他阵列获取组合

I have two array

First

array(
0 => 100000,
1 => 50000,
2 => 100000,
3 => 100000);

Second

array(
0 => 150000,
1 => 200000,);

The problem is I want to get the combination from first array that formed each second array.

Example Second array index 0 can be formed from first array index 0 and 1 and second array index 1 can be formed from first array index 2 and 3

I want to achieve like this

[0 => [0,1] , 1 => [2,3]]

Thanks for the help.

Try with following code:

$arr = array(
0 => 100000,
1 => 50000,
2 => 100000,
3 => 100000);
$count = $val = 0;
$newArr = [];
foreach($arr as $a){
   $val += $a;
   $count++;
   if($count == 2){
     $newArr[] = $val;
     $val = $count = 0; 
   }
}
print_r($newArr); die;

A simple an fast gready approach would be to first sort the arrays descending. After that, loop over the second one and collect from the first one as much values, till you reach your desired value.

$first = [
    0 => 100000,
    1 => 50000,
    2 => 100000,
    3 => 100000
];

$second = [
    0 => 150000,
    1 => 200000
];

arsort($first);
arsort($second);

$combinations = [];
foreach ($second as $search) {
    $combination = [];
    $sum = 0;
    foreach ($first as $key => $val) {
        if ($sum + $val > $search) continue;
        $sum += $val;
        $combination[] = $key;
        if ($sum == $search) break;
    }
    if ($sum != $search) die("nothing found this way..");
    foreach ($combination as $val) unset($first[$val]);
    $combinations[] = $combination;
}

print_r($combinations);

Here is the simple idea to achieve your requirement. There would be many if's and but you need to consider yourself

<?php
$arr1 = [0 => 100000,1 => 50000,2 => 100000,3 => 100000];
$arr2 = [0 => 150000,1 => 200000];
//$arr2 = [0 => 250000,1 => 100000];
$count = 0;
$new = array();
for($i=0;$i<count($arr1);$i++){

  if($arr1[$i] == $arr2[$count]){
     $new[$arr2[$count]] = $arr1[$i];
     $count++;
  }else{
    $sum = [$arr1[$i]];
    for($j=$i+1;$j<count($arr1);$j++){
      $sum[] = $arr1[$j];
      if( array_sum($sum) == $arr2[$count]){
        $new[$arr2[$count]] = $sum;
        $count++;
      }
    }
  }  
}
print_r($new);
?>

Output1

Output2