PHP: Algorithm Discount Balances

0

It turns out that I am starting in this world of programming and in a PHP course that I am doing, they ask me to do an algorithm to discount Balances, this must:

  • Discount balance to the first ID that has available balance
  • If the used one surpasses what is available, it must go to the next line.

I had everything right in the beginning, but it always discounted me in all the IDs and I can not make it stop. It has me very frustrated, since on paper it is addition and subtraction. I would greatly appreciate if someone could help me to "unlock". Thank you very much!

$a[0]['ID'] = "1";
$a[0]['DISPONIBLE']="15";
$a[0]['UTILIZADO']="15";
$a[1]['ID'] = "2";
$a[1]['DISPONIBLE']="15";
$a[1]['UTILIZADO']="6";
$a[2]['ID'] = "3";
$a[2]['DISPONIBLE']="15";
$a[2]['UTILIZADO']="0";


$b = 7; // SALDO A DESCONTAR

for($c = 0 ; $c < count($a) ; $c++){

    if($a[$c]['DISPONIBLE'] > $a[$c]['UTILIZADO']){

        $a[$c]['UTILIZADO'] += $b;
    }
}
print_r($a);
echo "</pre>";
    
asked by arium2000 10.07.2017 в 17:24
source

2 answers

0

It will be enough to indicate a break the first time the condition is fulfilled.

if($a[$c]['DISPONIBLE'] > $a[$c]['UTILIZADO']){
    $a[$c]['UTILIZADO'] += $b;
    break;
}

The break breaks the cycle and you will only increase the Used Balance of the first ID with sufficient Available Balance.

    
answered by 10.07.2017 / 18:03
source
0

$a[0]['ID'] = "1";
$a[0]['DISPONIBLE']="15";
$a[0]['UTILIZADO']="15";
$a[1]['ID'] = "2";
$a[1]['DISPONIBLE']="15";
$a[1]['UTILIZADO']="6";
$a[2]['ID'] = "3";
$a[2]['DISPONIBLE']="15";
$a[2]['UTILIZADO']="0";


$b = 7; // SALDO A DESCONTAR

for($c = 0 ; $c < count($a) ; $c++){

if($a[$c]['DISPONIBLE'] > $a[$c]['UTILIZADO']){

    $disponible = $a[$c]['DISPONIBLE'] - $a[$c]['UTILIZADO'];

    if($disponible <= $b){
	    $a[$c]['UTILIZADO'] += $disponible;
	    $b -= $disponible;
    }else{
        $a[$c]['UTILIZADO'] += $b;
	    $b -= $b;
    }
}
if($b == 0){
   break;
}
}
print_r($a);
echo "</pre>";
    
answered by 10.07.2017 в 17:52