1
<?php 
    $c = count($rank); // 5

    for ($i = 0; $i < $c; $i++) {
        $labels [] = array("value" =>$i, "text" => $i);
    }

?>

output: `[{"value":1,"text":1},{"value":2,"text":2},{"value":3,"text":3},{"value":4,"text":4},{"value":5,"text":5}]`

But what I need is:

[{"value":5,"text":1},{"value":4,"text":2},{"value":3,"text":3},{"value":2,"text":4},{"value":1,"text":5}]

Any idea about that?

5 Answers 5

4

I'll describe my line of thinking.

What is the pattern in the sequence 5, 4, 3, 2, 1? Quite clearly, I decrease by one each time. I already know that $i increases by one each time, because that is how we wrote our for loop. My goal and what is available with $i is fairly close, so is there any way I can use $i?

Indeed there is. Instead of saying the sequence 5, 4, 3, 2, 1 decreases by one each time, I can say that the sequence increases in its distance from 5 by one each time. That is, the sequence is equivalent to 5 - 0, 5 - 1, 5 - 2, 5 - 3, 5 - 4. Notice that this lines up perfectly with $i. Therefore, our solution can be the following:

<?php 
$c = count($rank); // 5

for ($i = 0; $i < $c; $i++) {
      $labels [] = array("value" =>($c - $i), "text" => $i);
}

This takes a bit of intuition to see, and if you are in a similar situation and cannot figure out the pattern, you can always introduce a new variable.

<?php 
$c = count($rank); // 5


for ($decreasing = $c, $i = 0; $i < $c; $i++, --$decreasing) {
      $labels [] = array("value" =>$decreasing, "text" => $i);
}
Sign up to request clarification or add additional context in comments.

Comments

2

Are you just wanting the value to decrement by one every time? If so subtract the iterator count from the total count:

<?php 
    $c = count($rank); // 5

    for ($i = 0; $i < $c; $i++) {
        $labels [] = array("value" =>($c - $i), "text" => $i);
    }

 ?>

Comments

1
<?php 
$c = count($rank); // 5
$j = $c;
for ($i = 0; $i < $c; $i++) {
    $labels [] = array("value" =>$j, "text" => $i);
    $j --;
}
?>

Comments

0

How about

$labels [] = array("value" => ($c - $i), "text" => ($i + 1));

Comments

0

The code you show won't produce that array because $i iterates over 0...4 whereas the values in your array are 1...5. But it appears that what you need to do is to change the statement inside the for loop to

$c = count($rank); // 5

for ($i = 0; $i < $c; $i++) {
  $labels[] = array("value" =>5-$i, "text" => $i+1);
}

or perhaps using array_map

$c = count($rank); // 5
$labels = array_map(function ($n) {
  return array("value" => 6-$n, "text" => $n);
}, range(1, $c));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.