我已经更改了这个递归函数的版本... http://www.phpbuilder.com/articles/databases/mysql/handling-hierarchical-data-in-mysql-and-php.html
我需要的是一种在数组中保存此函数的返回值的方法,以便我可以反转数组元素的顺序。该功能对我很有用,但我需要一种方法来保存值。这是代码......
function display_children($category_id, $level) {
global $database;
$result = mysql_query("SELECT * FROM parents WHERE id_roditelja='$category_id'") or die(mysql_error());
$niz = array();
while ($row = mysql_fetch_array($result)) {
echo str_repeat(' ', $level) . $row['naziv'] . "<br/>";
array_push($niz, display_children($row['parent_id'], $level + 1));
//this is one way I tried, and I get $niz with exact number of elements but each is null
//in this $niz array I need to store values of recursion
var_dump($niz);
}
}
答案 0 :(得分:1)
我想你想要这个:
function display_children/* <- this must be the same */($category_id, $level) {
global $database;
$result = mysql_query("SELECT * FROM parents WHERE id_roditelja='$category_id'") or die(mysql_error());
$niz = array();
while ($row = mysql_fetch_array($result)) {
$niz[] = str_repeat(' ', $level) . $row['naziv'] . "<br/>"; // we need to save this
$niz = array_merge($niz, /* as this -> */display_children($row['parent_id'], $level + 1)); // array_merge doesn't take a reference so we need to store its result in $niz
}
return $niz;
}
如果你想要一个类似树的结构,请使用array_push而不是array_merge。 似乎没有人注意到:如果没有回复陈述,他的功能就无法返回任何东西!