How do you reduce the values in an array one by one?

Asked 2 months ago, Updated 2 months ago, 1 views

There is an associative array with value = integer type.
I have reduced this value for each particular Key order, but if there is a non-cool implementation or efficient method, please let me know.

code:

$array=['banana'=>3,'orange'=>2,'apple'=>2];

//banana->orange->Apple.

$subtraction = 3; // Decrease

for($i=0;$i<$subtraction;$i++)
{
    if($array['banana']>0&&($i===0||$i===3||$i===6)){$array['banana']--;continue;}
    if($array['orange']>0&&($i===1||$i===4){$array['orange']--;continue;}
    if($array['apple']>0&&($i===2||$i===5)){$array['apple']--;continue;}
}

php

2022-09-30 14:28

2 Answers

Reduce banana->orange->apple

We have simplified the branch conditions of the .
$i_mod=$i%count($array); gets the remainder of the number of array elements defined.

$array=['banana'=>3,'orange'=>2,'apple'=>2];

//banana->orange->Apple.
// Change the order of $array registration when changing the order

$subtraction = 3; // Decrease

$array_key=[]; // Create an array so that it can be accessed by a number.
foreach($array as$key=>$value){
  $array_key[] = $key;
}

for($i=0;$i<$subtraction;$i++)
{
  $i_mod = $i%count($array); // $i%3
  $key = $array_key[$i_mod];
  if($array[$key]>0){
    $array[$key]--;
  }
}

I think the reason why I think it's not cool is because I don't understand it.


2022-09-30 14:28

As I mentioned in the comment, the posted code does not decrement if the array value is 0, but decrements the value of $subtraction.
The following specification assumes that if the array value is 0, the value of $subtraction should remain the same.

<?php

$array=['banana'=>2,'orange'=>1,'apple'=>6];
$order=['banana', 'orange', 'apple']; // decreasing order
$subtraction=7; // Number to decrease

$subtraction=min($subtraction,array_sum($array)));
$len=count($order);
for($i=0;$subtraction;$i=(++$i)%$len){
    if($array[$order[$i]]]>0){
        $array[$order[$i]]--;
        $subtraction--;
    }
}

print_r($array);

//
// array
// (
//     [banana] = > 0
//     range = > 0
//     [Apple] =>2
// )


2022-09-30 14:28

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.