首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在数组for循环中添加0到数字

如何在数组for循环中添加0到数字
EN

Stack Overflow用户
提问于 2018-07-30 18:09:11
回答 1查看 149关注 0票数 1

我试图添加每次当数字是平的或等于2长度的0。例如:我不想要a1,a10,我想要a01,a10

代码语言:javascript
复制
$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,b03,en19#,,en28#

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-30 18:32:09

代码语言:javascript
复制
<?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, ',');
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51599915

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档