What is the solution to loop nesting with an uncertain number of levels in PHP?
你心哥我啦
你心哥我啦 2021-05-21 20:33:26
0
1
893

Problem description: The following numbers are all passed parameters 1. Give an unknown number of product price ranges and the maximum quantity that can be sold, the lowest selling price, the highest selling price, and the largest quantity. Product A 1105 1115 29 Product B 1605 1620 33 Product C 2005 2025 172. Given the fixed total sales amount of this order, 14850

, the post parameter of the above question can be expressed as:

$arr[0][‘low’]=1105;
$arr[0][‘high’]=1115;
$arr[0][‘num’]=29;
$arr[1][‘low’]=1605;
$arr[1][‘high’]=1620;
$arr[1][‘num’]=33;
$arr[2][‘low’]=2005;
$arr[2][‘high’]=2025;
$arr[2][‘num’]=17;
$total=14850;

Asking: How many combinations of sales are there and the array is returned? The key point is that the number of one-dimensional parameters passed each time is uncertain, that is, there may be 100 products that need to be calculated.

It is very simple to write it down directly, but it cannot be encapsulated at all:

for ($a=1105; $a <= 1115; $a++) { 
 for ($b=1605; $b <= 1620; $b++) { 
   for ($c=2005; $c <= 2025 ; $c++) { 
     for ($x=0; $x <= 19; $x++) { 
       for ($y=0; $y <= 30 ; $y++) { 
         for ($z=0; $z <= 10 ; $z++) { 
           if ($a*$x + $b*$y +$c*$z == 14850) {
             echo $a."*".$x ."+". $b."*".$y."+". $c."*".$z."<br>";
           }
         }
        }
     }
   }
 }
}

The problem lies in the uncertainty of the types and quantities of the incoming products. This uncertainty How many times does it need to be looped and what ideas should be used to solve it?

你心哥我啦
你心哥我啦

reply all(1)
Peter_Zhu

It is not a good idea to use nested loops if you are not sure about the level

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template