【问题标题】:How to add 0 to number in array for loop如何将0添加到数组for循环中的数字
【发布时间】:2019-01-07 01:19:34
【问题描述】:

每当数字大于或等于 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

【问题讨论】:

标签: php arrays string for-loop


【解决方案1】:
<?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, ',');

【讨论】:

  • 干得好。谢谢。
猜你喜欢
  • 2020-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多