我想我想要的是一个递归函数,但是如果有另一种方法可以实现我想要做的,请告诉我!我不确定我是否会很好地解释这一点,所以如果您需要进一步澄清,请告诉我。
我有一个函数 findSeed() ,它接受一个 id 并返回一个数组,其中包含有关“种子”的信息:
function findSeeds($id) {
global $wpdb;
$query = "SELECT * FROM seedTable WHERE id = " . $id;
$seed = $wpdb->get_row($query, ARRAY_A);
return $seed;
}
它返回以下数组:
Array
(
[id] => 9
[name] => Sign
[seed1] => 4
[seed2] => 3
)
其中种子 1 和种子 2 是创建它所需的种子的 ID。我正在寻找一个函数来创建一个多维数组,格式如下,其中数组的第一部分包含第一个“种子”,下一个包含第一个中包含的两个种子,下一个包含两个每个种子中都包含种子,依此类推:
Array
(
[1] => Array
(
[0] => Stripey Wallpaper
)
[2] => Array
(
[0] => Green Block
[1] => Aqua Block
)
[3] => Array
(
[0] => Bricks
[1] => Grass
[2] => Bricks
[3] => Glass Pane
)
[4] => Array
(
[0] => Rock
[1] => Grass
[2] => Dirt
[3] => Rock
[4] => Rock
[5] => Grass
[6] => Rock
[7] => Lava
)
)
到目前为止,我正在使用此处显示的(可怕的)功能来完成它,但是“地图”可能是 2 到 8 行之间的任何内容,我正在努力了解如何将其变成一个适用于的简洁小功能任何事物:
function makeMap($id) {
// First Row
$rowNum = 1;
$oneSeed = findSeeds($id);
$map[$rowNum][] = $oneSeed[name];
// Second Row
$rowNum = $rowNum + 1;
$twoSeed = findSeeds($oneSeed[seed1]);
$threeSeed = findSeeds($oneSeed[seed2]);
$map[$rowNum][] = $twoSeed[name];
$map[$rowNum][] = $threeSeed[name];
// Third Row
$rowNum = $rowNum + 1;
$fourSeed = findSeeds($twoSeed[seed1]);
$fiveSeed = findSeeds($twoSeed[seed2]);
$sixSeed = findSeeds($threeSeed[seed1]);
$sevenSeed = findSeeds($threeSeed[seed2]);
$map[$rowNum][] = $fourSeed[name];
$map[$rowNum][] = $fiveSeed[name];
$map[$rowNum][] = $sixSeed[name];
$map[$rowNum][] = $sevenSeed[name];
// Fourth Row
$rowNum = $rowNum + 1;
$eightSeed = findSeeds($fourSeed[seed1]);
$nineSeed = findSeeds($fourSeed[seed2]);
$tenSeed = findSeeds($fiveSeed[seed1]);
$elevenSeed = findSeeds($fiveSeed[seed2]);
$twelveSeed = findSeeds($sixSeed[seed1]);
$thirteenSeed = findSeeds($sixSeed[seed2]);
$fourteenSeed = findSeeds($sevenSeed[seed1]);
$fifteenSeed = findSeeds($sevenSeed[seed2]);
$map[$rowNum][] = $eightSeed[name];
$map[$rowNum][] = $nineSeed[name];
$map[$rowNum][] = $tenSeed[name];
$map[$rowNum][] = $elevenSeed[name];
$map[$rowNum][] = $twelveSeed[name];
$map[$rowNum][] = $thirteenSeed[name];
$map[$rowNum][] = $fourteenSeed[name];
$map[$rowNum][] = $fifteenSeed[name];
return $map;
}
它应该在所有“行”节点为空时停止,因此以下只需要返回前两个“行”:
Array
(
[1] => Array
(
[0] => Wood Block
)
[2] => Array
(
[0] => Dirt
[1] => Lava
)
[3] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
)
[4] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
[5] =>
[6] =>
[7] =>
)
)
任何提示、提示或解决方案将不胜感激,
谢谢你。
编辑:快速说明为什么我喜欢上述格式 - 然后我将结果打印在表格中,第一个种子跨越整行,然后将其与下面的孩子一起分解,如下所示:
$map = makeMap($_POST['theItem']);
$colspan = count(end(array_values($map)));
echo '<h3>' . $map[row1][0] . '</h3><br/>';
echo '<table>';
foreach ($map as $row) {
echo '<tr>';
foreach ( $row as $cell) {
echo '<td colspan="'. $colspan .'"><div class="seed">' . $cell . '</div></td>';
}
$colspan = $colspan / 2;
echo '</tr>';
}
echo '</table>';