简体   繁体   中英

Compare array values to calculate % in PHP?

So the goal is to be able to create a dynamic value for my progress bar based on dynamic variables from the database. Below is a pseudo code for what i am looking for if its possible:

//League rank names
['bronze_V','bronze_IV','bronze_III','bronze_II','bronze_I'];

Lets say i start at bronze_IV to bronze_II i need to calculate that to 100?
and then i need to store that value is that possible to be dynamic?

are you trying something like this,

$data = ['bronze_V','bronze_IV','bronze_III','bronze_II','bronze_I'];

$start = $end = 0;

while($element = current($data)) {
    if ($element == 'bronze_IV') $start = key($data);
    if ($element == 'bronze_I') $end = key($data);
    next($data);
}

$percentage = ( (($end-$start) + 1) / count($data) ) * 100;

var_dump($percentage); //float(80)

example with multiple tiers,

#note : badge count for each tier has to be 5 for this to work, 
#if you change the count change change the value inside the loop

$data = array(
        ['silver_V','silver_IV','silver_III','silver_II','silver_I'],
        ['bronze_V','bronze_IV','bronze_III','bronze_II','bronze_I']
    );

$start = $end = 0;

$start_badge = 'silver_V';
$end_badge = 'bronze_II';

//loop through tiers
foreach ($data as $key => $tier) {
    //loop through badges
    while($badge = current($tier)){
        //position of the start badge
        if ($badge == $start_badge) $start = ($key * 5) + key($tier)+1; //see note 
        //position of the end badge
        if ($badge == $end_badge) $end = ($key * 5) + key($tier)+1; //see note
        next($tier);
    }
}

//count badges
$badges_count = (count($data, COUNT_RECURSIVE) - count($data));

//calculate percentage
$percentage = ( (($end-$start) + 1) / $badges_count ) * 100;

var_dump($percentage); //float(90)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM