【问题标题】:array output structure数组输出结构
【发布时间】:2012-02-04 16:06:17
【问题描述】:
<?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}]`

但我需要的是:

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

对此有什么想法吗?

【问题讨论】:

    标签: php arrays for-loop


    【解决方案1】:

    我将描述我的思路。

    5, 4, 3, 2, 1 序列中的模式是什么?很明显,我每次减一。我已经知道$i 每次增加一,因为这就是我们编写 for 循环的方式。我的目标和$i 可用的功能相当接近,那么我有什么办法可以使用$i 吗?

    确实有。与其说序列5, 4, 3, 2, 1 每次减一,我可以说序列增加 从5 开始的距离每次加一。即,序列等价于5 - 0, 5 - 1, 5 - 2, 5 - 3, 5 - 4。请注意,这与$i 完全一致。因此,我们的解决方案可以是:

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

    这需要一点直觉才能看出来,如果你遇到类似的情况,无法弄清楚模式,你总是可以引入一个新的变量。

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

    【讨论】:

      【解决方案2】:

      您是否只想让值每次减一?如果是这样,从总计数中减去迭代器计数:

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

      【讨论】:

        【解决方案3】:
        <?php 
        $c = count($rank); // 5
        $j = $c;
        for ($i = 0; $i < $c; $i++) {
            $labels [] = array("value" =>$j, "text" => $i);
            $j --;
        }
        ?>
        

        【讨论】:

          【解决方案4】:

          怎么样

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

          【讨论】:

            【解决方案5】:

            您显示的代码不会生成该数组,因为$i 迭代了 0...4,而您的数组中的值为 1...5。但是看来您需要做的是将for循环内的语句更改为

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

            或者也许使用array_map

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

            【讨论】:

              猜你喜欢
              • 2021-03-04
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-08-19
              • 1970-01-01
              • 1970-01-01
              • 2012-07-12
              • 2016-06-12
              相关资源
              最近更新 更多