我的PHP代码如下所示:
function generate_sections() {
$puzzle = [];
// sections
for ($i = 0; $i < 9; $i++) {
// cells
function generate_cells() {
$section = [];
for ($i = 0; $i < 9; $i++) {
$random_number = rand(1, 9);
if (!in_array($random_number, $section)) {
array_push($section, $random_number);
} else {
return generate_cells();
}
}
}
array_push($puzzle, $section);
}
return $puzzle;
}
var_dump(generate_sections());
第二个for循环必须生成唯一的数字并将它们添加到sections []数组中。当我从第一个循环中取出第二个循环时,这工作正常。但是,当像这样写它时,generate_cells()函数不会再发生,它会给我以下错误:
Fatal error: Cannot redeclare generate_cells() (previously declared in /Applications/AMPPS/www/sudoku/index.php:38) in /Applications/AMPPS/www/sudoku/index.php on line 37
答案 0 :(得分:2)
您正在声明功能&#34; generate_cells&#34;在循环中。在第二次循环执行时,当已经声明了函数时,您会收到致命错误 它必须是这样的:
function generate_sections()
{
$puzzle = [];
// sections
for ($i = 0; $i < 9; $i++) {
// cells
$section = generate_cells();
array_push($puzzle, $section);
}
return $puzzle;
}
function generate_cells()
{
$section = [];
for ($i = 0; $i < 9; $i++) {
$random_number = rand(1, 9);
if (!in_array($random_number, $section)) {
array_push($section, $random_number);
} else {
return generate_cells();
}
}
return $section;
}
var_dump(generate_sections());