-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwidget-test.php
More file actions
115 lines (82 loc) · 2.09 KB
/
Copy pathwidget-test.php
File metadata and controls
115 lines (82 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<?
if(isset($_POST['submit']))
{
$qtyOrdered = $_POST['num-of-widgets'];
// if over 5000 need to break it down
if($qtyOrdered > 5000)
{
$packsToOrder = array();
$newQtyOrdered = floor($qtyOrdered / 5000);
// loop through each 5000
for($i = 0; $i < floor($newQtyOrdered); $i++)
{
$packsToOrder[] = '1 x 5000';
}
$qtyLeft = $qtyOrdered - ($newQtyOrdered * 5000);
// pass through the remaining widgets to our recursive function
$packsToOrder = recurse($qtyLeft, $packsToOrder);
}
else
{
$packsToOrder = recurse($qtyOrdered);
}
}
function recurse($qtyOrdered, &$packsToOrder = array())
{
$widgetPacks = array(
250,
500,
1000,
2000,
5000
);
$widgetPacksReversed = array_reverse($widgetPacks);
foreach($widgetPacksReversed as $key => $widgetPackQty)
{
// if exact match
if($qtyOrdered == $widgetPackQty)
{
$packsToOrder[] = '1 x'.$widgetPackQty;
return $packsToOrder;
}
$nextKey = $key + 1;
$nextNextKey = $key + 2;
$previousKey = $key - 1;
//if between two pack numbers (500 and 1000. Current is 1000)
if (($qtyOrdered < $widgetPackQty) && ($qtyOrdered > $widgetPacksReversed[$nextKey]))
{
$newQty = $qtyOrdered - $widgetPacksReversed[$nextKey];
if($newQty < $widgetPacksReversed[$nextNextKey])
{
$packsToOrder[] = '1 x '.$widgetPacksReversed[$nextKey];
recurse($newQty, $packsToOrder);
}
else
{
$packsToOrder[] = '1 x '.$widgetPackQty;
}
}
}
return $packsToOrder;
}
?>
<h1>Widget Order Program</h1>
<p>Please enter number of widgets you would like to purchase and
the program will work out what packs will need ordering</p>
<form method="POST" action="http://localhost/flatten-json-test/widget-test.php">
<p>Number of widgets to order: <input name="num-of-widgets" type="text" /></p>
<p><input name="submit" type="submit" value="Submit" /></p>
</form>
<?
// print results to screen
if(isset($_POST['submit']))
{
echo '<h3>Packs to order</h3>';
echo '<ul style="color:green;">';
foreach($packsToOrder as $currentPack)
{
echo '<li>'.$currentPack.'</li>';
}
echo '</ul>';
}
?>