简体   繁体   中英

Create two-dimensional array by using 2 loops

I need to create two-dimensional array by using 2 loops. Array must look like this: [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

This is what I tried, but I wanted to see better solution and to know is my solution bad.

<?php
$arr = [];
$elem = 1;

for ($i = 0; $i <= 2; $i++) {
   for ($j = 1; $j <= 3; $j++) {
       $arr[$i][] = $elem++;
   }
}
?>
$number = range(1,9);
print_r (array_chunk($number,3));

One of hundreds options:

$arr = [
    range(1, 3), 
    range(4, 6), 
    range(7, 9), 
];
print_r($arr);

Others have shown you some clever ways, but keeping it simple in case you are just starting out with programming.... In the inner loop, create a temporary array, then outside the inner loop but inside the outer, add it to your main array.

$arr = [];
$elem = 1;

for ($i = 0; $i <= 2; $i++) {
    $t = []; #Init empty temp array
    for ($j = 1; $j <= 3; $j++) {
        $t[] = $elem++;
    }
    $arr[] = $t;
}

one method: this method use "temp variables".

<?php
$arr_inner = [];
$arr_main = [];
$elem=1;

for ($i = 0; $i <= 2; $i++) {
   for ($j = 0; $j <= 2; $j++) {
    $elem =$elem +1;
       $arr_inner[$j]  = $elem;
   }
    $arr_main[$i] = $arr_inner;
    unset($arr_inner);
}
?>

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