I have an array of poll options, and an array that is a set of poll results (votes). With this code I cycle in all the options outputting a progress bar with the votes. What I need to to is to sort the options by results (most voted first), but I can't understand if and how it's possible to do it starting from here.
<? foreach ($poll["options"] as $optionKey => $option) {
$answer = $pollAnswerSet["answers"][$optionKey];
$absolutePerc = $sum == 0 ? 0 : floor($answer/$sum * 100);
?>
<div>
<div class='progress-bar' style="width:<?= $absolutePerc ?>%;"></div>
<?= "$absolutePerc%" ?>
</div>
<? } ?>
CodePudding user response:
Without seeing the data, it looks like you just sort the answers and then loop that. You can use the answers key to access the option (if needed).
arsort
will sort highest to lowest and maintain the keys:
arsort($pollAnswerSet["answers"]);
<?php foreach ($pollAnswerSet["answers"] as $key => $val) {
$option = $poll["options"][$key];
$absolutePerc = $sum == 0 ? 0 : floor($val/$sum * 100);
?>
<div>
<div class='progress-bar' style="width:<?= $absolutePerc ?>%;"></div>
<?= "$absolutePerc%" ?>
</div>
<?php } ?>
As short tags can be disabled it is recommended to only use the normal tags (<?php ?>
and <?= ?>
) to maximise compatibility.