【问题标题】:PHP: print for loop index to data size dynamic by $i valuePHP:通过 $i 值将 for 循环索引打印到动态数据大小
【发布时间】:2018-04-20 01:12:26
【问题描述】:

请问我怎样才能实现这样的目标:

A-FIRSTNAME
B-LASTNAME
C-MIDDLENAME
D-PHONE

她是我的密码

<php 

   $alphabet = range('A','D');
   for ($i = 1; $i<4; $i++){
      $i2 = $i;
      echo $alphabet[$i2]."-FIRSTNAME";
      echo $alphabet[$i2]."-LASTNAME";
      echo $alphabet[$i2]."-MIDDLENAME";
      echo $alphabet[$i2]."-PHONE";
      $i2++;
  }

?>

【问题讨论】:

    标签: php phpoffice


    【解决方案1】:

    你可以这样做:

    $arr = array('FIRSTNAME','LASTNAME','MIDDLENAME','PHONE');
    
    $i = 0;
    foreach (range('A', 'D') as $alphabet) {
        echo $alphabet .'-'. $arr[$i] . '\n';
        $i++;
    }
    

    【讨论】:

      【解决方案2】:

      PHP > 7:

      <?php
      $phrases = [
          'FIRSTNAME', 
          'LASTNAME', 
          'MIDDLENAME',
          'PHONE'
      ];
      $chars  = range('A','Z');
      foreach ($phrases as $index => $phrase) {
          echo ($chars[$index] ?? '?') . ' => ' . $phrase;
      }
      

      PHP

      <?php
      $phrases = [
          'FIRSTNAME', 
          'LASTNAME', 
          'MIDDLENAME',
          'PHONE'
      ];
      $chars  = range('A','Z');
      foreach ($phrases as $index => $phrase) {
          echo (isset($chars[$index]) ? $chars[$index] : '?') . ' => ' . $phrase;
      }
      

      【讨论】:

        【解决方案3】:
        <?php 
        
           $alphabet = range('A','D');
        
        
           for ($i = 0; $i<4; $i++){
        
              echo nl2br($alphabet[$i]."-FIRSTNAME\n");
              echo nl2br($alphabet[$i]."-LASTNAME\n");
              echo nl2br($alphabet[$i]."-MIDDLENAME\n");
              echo nl2br($alphabet[$i]."-PHONE\n");
              echo nl2br("\n");
              echo nl2br("\n");
          }
        
        ?>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-08
          • 1970-01-01
          • 2021-07-01
          • 1970-01-01
          • 2011-10-07
          • 1970-01-01
          相关资源
          最近更新 更多