0

我已经改变了这个递归函数的版本...... 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);
  }
}
4

1 回答 1

2

我想你想要这个:

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。似乎没有人注意到:没有 return 语句,他的函数不能返回任何东西!

于 2013-08-28T09:02:53.360 回答