如何为循环中的数字加0

时间:2018-07-30 18:09:11

标签: php arrays string for-loop

每次数字大于或等于2时,我都尝试添加0。例如:我不需要a1,a10,我想要a01,a10

$a_l_demographics = [11,3,13];
$a_p_demographics  = ['a','b','c'];
$a_r_demographics = [];
$c_demographics_values = array();
$a_c_demographics = min(count($a_l_demographics), count($a_p_demographics));

for ($i = 0; $i < $a_c_demographics; $i++) {

  for ($j = 1; $j <= $a_l_demographics[$i]; $j++) {

    $a_r_demographics[] = $a_p_demographics[$i] . $j;

    // I tried to do something like this, but doesn't work.
    if (strlen(implode($a_r_demographics)) >= 2) {
      $a_r_demographics[] = '0'.$a_p_demographics[$i] . $j;
    } else {
      $a_r_demographics[] = $a_p_demographics[$i] . $j;
    }

    // or even this
    /*
    switch (true) {
      case $i <= 10:
        $a_r_demographics[] = '0'.$a_p_demographics[$i] . $j;
        break;
    }
    */

    echo implode($a_r_demographics);

  }

}

结果应为:

a01,a02,a03,a04,a05,a06,a07,a08,a09,a10,a11,b01,b02,b03,c01,c02,c03,c04,c05,c06,c07,c08, c09,c10,c11,c12,c13

1 个答案:

答案 0 :(得分:2)

<?php
    $a_l_demographics = [11,3,13];
    $a_p_demographics  = ['a','b','c'];
    $a_r_demographics = [];
    $c_demographics_values = array();
    $a_c_demographics = min(count($a_l_demographics), count($a_p_demographics));

    for ($i = 0; $i < $a_c_demographics; $i++) {
        for ($j = 1; $j <= $a_l_demographics[$i]; $j++) {
            $a_r_demographics[] = $a_p_demographics[$i] . str_pad($j, 2, 0, STR_PAD_LEFT);
        }
    }
    echo implode($a_r_demographics, ',');