[英]How Can I Check For The Closest Array Value, Deduct It From The Variable And Then Re-Check It, Echoing Each Time
$widgetsRequested = 2467; // Our magic variable - user input
echo 'Original Number:';
echo $widgetsRequested;
echo '<br>';
$widgetBatches = array("250", "500", "1000", "2000");
rsort($widgetBatches);
foreach ($widgetBatches as $key => $val) {
} // Reverse sort values
$processWidgetTotal = $widgetBatches; // Pass it on to process
function compareWidgets1($processWidgetTotal, $number) { // run this once to compare
sort($processWidgetTotal);
foreach ($processWidgetTotal as $a) {
if ($a >= $number) return $a;
}
return end($processWidgetTotal);
}
echo 'Our Closest Matching Batch is: ';
echo $totalRemaining1 = compareWidgets1($processWidgetTotal, $widgetsRequested); // Go through and find the closest match within the widgetBatches array
echo '<br>';
echo 'Left To Allocate: ';
echo $newWidgetTotal1 = $widgetsRequested - $totalRemaining1; // Go through and find the closest match within the widgetBatches array
echo '<br>';
我需要做的是讓用戶輸入($ widgetsRequested)與compareWidgets1函數(檢查$ widgetBatches數組中最接近的匹配項)進行比較,然后回顯最接近的匹配項,從用戶輸入中扣除它,然后再次循環直到$ widgetsRequested達到0或第一個否定結果(即-5)。
我在想我需要一個dowhile循環嗎? 但是我無法讓該功能直接位於其中,請幫忙嗎?
這就是我如何解決您的問題:
public $iterations = 0;
private function Widget($userinput)
{
$this->iterations++;
$widgetRequested = $userinput;
$widgetBatches = array("250", "500", "1000", "2000");
echo "Iteration " . $this->iterations;
echo "<br/>";
echo "Widget requested: " . $widgetRequested;
echo "<br/>";
$closest = $this->GetClosest($widgetBatches, $widgetRequested);
echo "Closest: " . $closest;
echo "<br/>";
$widgetRemaining = $widgetRequested - $closest;
echo "Remainder: " . $widgetRemaining;
echo "<hr/>";
if($widgetRemaining > 0)
{
$this->Widget($widgetRemaining);
}
else
{
echo "The value is now below or equaling zero: " . $widgetRemaining . "!";
}
}
//Code is from: http://stackoverflow.com/questions/5464919/php-nearest-value-from-an-array
private function GetClosest(array $array, $value)
{
$lowest = null;
foreach($array as $val)
{
if($lowest == null || abs($value - $lowest) > abs($val - $value))
{
$lowest = $val;
}
}
return $lowest;
}
**注意:這是在我當前的項目中進行的,可能需要對$ this關鍵字進行一些其他更改。*
基本上,我們正在做的是獲取最接近的匹配,並存儲該值。 在那之后,我們用最接近和用戶輸入的結果減去它。 然后,我們執行一個if子句以查看是否小於零。 如果沒有,我們將使用剛剛生成的值再次調用該函數。
輸出:
Iteration 1
Widget requested: 2467
Closest: 2000
Remainder: 467
Iteration 2
Widget requested: 467
Closest: 500
Remainder: -33
The value is now below or equaling zero: -33!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.