問題:
MySQLの関数とデータを使用して再帰ツリーを構築しようとしています。ただし、結果は期待どおりではありません。
PHPコード:
function buildTree($root, $next = array())
{
// Sanitize input
$root = (int) $root;
// Do query
$query = "SELECT CID, Item, Parent FROM betyg_category WHERE Status = '1' AND Parent = '{$root}'";
$result = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error());
// Loop results
while ($row = mysql_fetch_assoc($result))
{
$next[$row['CID']] = array (
'CID' => $row['CID'],
'Item' => $row['Item'],
'Parent' => $row['Parent'],
'Children' => buildTree($row['CID'], $next)
);
}
// Free mysql result resource
mysql_free_result($result);
// Return new array
return $next;
}
$testTree = buildTree(0);
echo "<xmp>".print_r($testTree, true)."</xmp>";
データベース内のテーブルは次のようになります。
配列を次のようにしたいと思います。
Array
(
[1] => Array
(
[CID] => 1
[Item] => Litteratur
[Parent] => 0
[Children] => Array
(
[2] => Integration av källorna
[3] => Belysning av egna resultat
[4] => Referenser
)
)
and so forth..
)
つまり、親ごとに=>子を作成してから、次の親に移動するなどです。アドバイスをよろしくお願いします。