Using forloop to populate brackets

主宰稳场 提交于 2020-01-07 01:58:26

问题


I want to learn to use for loop to populate brackets such as the following:- $max starts at 8 and can be maximum of 512. I only know very basics of forloop, not too well to form the below brackets.. can someone help me on this and explain how they done it. Each goes into simple pattern/sequence.

I appreciate it very much.

$max = 8;

if($max == 8)

[[0, 0], [0, 0]],   
[[0, 0], [0, 0]], 
[[0, 0]],
[[0, 0]]

if($max == 16)

[[0,0], [0,0], [0,0], [0,0]],
[[0,0], [0,0], [0,0], [0,0]],
[[0,0], [0,0]],
[[0,0], [0,0]],
[[0,0]],
[[0,0]]

if($max == 32)

[[0,0], [0,0], [0,0], [0,0], [0,0], [0,0], [0,0], [0,0]],
[[0,0], [0,0], [0,0], [0,0], [0,0], [0,0], [0,0], [0,0]],
[[0,0], [0,0], [0,0], [0,0]],
[[0,0], [0,0], [0,0], [0,0]],
[[0,0], [0,0]],
[[0,0], [0,0]],
[[0,0]],
[[0,0]]

etc until 512. Thanks


回答1:


So basically this would do:

$max = 8;
$arrays = array();
for($i = $max/4; $i >= 1; $i/=2) {
  $array = array_fill(0, $i, array(0,0));
  $arrays[] = $array;
  $arrays[] = $array;
}

And as a string:

$max = 8;
$arrays = array();
for($i = $max/4; $i >= 1; $i/=2) {
  $array = array_fill(0, $i, '[0,0]');
  $array = '['.implode(', ', $array).']';
  $arrays[] = $array;
  $arrays[] = $array;
}
$arrays = implode(",\n", $arrays);


来源:https://stackoverflow.com/questions/18449679/using-forloop-to-populate-brackets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!