简体   繁体   中英

Create array multidimensional from looping

I want to create array multidimensional from looping, but the results i want don't match expectations, here's my code:

$dayCount = 5;
for($i=1;$i<=$dayCount;$i++){
   $days[] = array($i<=9?"0".$i:$i => "string");
}

Result:

Array
(
    [0] => Array
        (
            [01] => string
        )
    [1] => Array
        (
            [02] => string
        )
    [2] => Array
        (
            [03] => string
        )
    [3] => Array
        (
            [04] => string
        )
    [4] => Array
        (
            [05] => string
        )
)

My Expected Result:

Array
(
    [01] => string
    [02] => string
    [03] => string
    [04] => string
    [05] => string
)

how to make it happen? Thanks in advance

This notation adds an array as an element to an array.

$array[] = array(..);

The result is a 2-dimensional array. To get a one-dimensional array with self-defined strings as key, do that:

$dayCount = 5;
for($i=1;$i<=$dayCount;$i++){
  $myKey = sprintf("%02d",$i);
  $days[$myKey] = "string";
}

Attention: for keys> 9, php will generate keys of type integer with this code.

Try with this, check the demo

$dayCount = 5;
for($i=1;$i<=$dayCount;$i++){
   $days[str_pad($i,2,'0',STR_PAD_LEFT)] = "string";
}
var_dump($days);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM