简体   繁体   English

带关联数组的PHP递归(菜单结构)

[英]PHP Recursion with Associative Array (Menu structure)

I've been banging my head against a wall today. 我今天一直在撞墙。 I have a mysql table that has a list of menu items which have a recursive parent/child relationship. 我有一个mysql表,其中包含具有递归父/子关系的菜单项列表。 I need to create an associative array that matches it. 我需要创建一个与其匹配的关联数组。

Here is my code, and below it is an explanation of my problem. 这是我的代码,下面是我的问题的解释。

MySQL Database MySQL数据库

CREATE TABLE IF NOT EXISTS `menus` (
  `sectionid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `parentid` int(10) unsigned NOT NULL DEFAULT '0',
  `name` varchar(128) NOT NULL DEFAULT '',
  PRIMARY KEY (`sectionid`)
);

INSERT INTO `menus` (`sectionid`, `parentid`, `name`) VALUES
(1, 0,'DOWNLOADS'),(4, 1,'Player Scenarios'),
(5, 1,'Co Op Scenarios'),(9, 1,'MAPS');

PHP CODE PHP代码

function get_db_children($parentid) {

  $mysqli = mysqli_open();
  $sqlStr = "select sectionid as childid from menus where parentid=$parentid order by sectionid";
  $result = $mysqli->query($sqlStr);
  $mysqli->close();

  return $result;

}

function get_children(&$node) {

  foreach ($node as $key=>$value) {
    $result = get_db_children($key);
    while ($row = $result->fetch_assoc()) {
       $tmp = array($row['childid'] => array());
       $node[$key][$row['childid']]= get_children($tmp);
    }
  }
  return $node;
}

=========================================== ==========================================

The above functions are called from my main script as follows: 从我的主脚本中调用上述函数,如下所示:

$categories[0] = array ();
get_children($categories);
print "Categories=".print_r($categories);
exit;

============== ==============

My PROBLEM. 我的问题。

My problem is that the structure of the returned array is not QUITE how I want it. 我的问题是返回数组的结构不是我想要的那样。

The code above returns: 上面的代码返回:

Categories=
Array ( [0] => Array 
        ( [1] => Array 
          ( [1] => Array 
            ( [4] => Array 
              ( [4] => Array ( ) )
              [5] => Array 
              ( [5] => Array ( ) )
              [9] => Array 
              ( [9] => Array ( ) )
            )
          )
        )
      ) 

What I want is: 我想要的是:

Categories=
Array ( [0] => Array 
          ( [1] => Array 
            (
              ( [4] => Array ( ) )
              ( [5] => Array ( ) )
              ( [9] => Array ( ) )
            )
          )
      )

A null array indicates no children. 空数组表示没有子级。

I can't figure out how to get rid of the double up on key values. 我不知道如何摆脱关键值的双重影响。 :( :(

If anyone can help, would be much appreciated. 如果有人可以帮助,将不胜感激。

Cheers, Nap 打ap

Changing the approach a little has fixed my problem. 稍微改变方法可以解决我的问题。 Instead of passing the $categories array by reference, I just pass the ID of the parent menu item and return the array. 我没有通过引用传递$categories数组,而是传递了父菜单项的ID并返回了该数组。

Code below uses same SQL data and SQL accessor function get_db_children($parentid) as given in my OP. 下面的代码使用与我的OP中相同的SQL数据和SQL访问器函数get_db_children($parentid) I'm sure this could be improved upon, but at least I've got my result. 我相信这可以改善,但至少我有结果。

@Josh, thnx for your input. @Josh,谢谢您的输入。

PHP Functions PHP函数

function get_twigs($nodeid) {

  $result = get_db_children($nodeid);
  if ($result->num_rows != 0) {
    while ($row = $result->fetch_assoc()) {
      $node[$row['childid']] = array();
      $node[$row['childid']] = get_twigs($row['childid']);
    }
  } else {
    $node=NULL; // or any other 'no children below me indicator.
  }
  return $node;
}

function get_branch($nodeid) {

  $node[$nodeid] = array();
  $node[$nodeid] = get_twigs($nodeid);
  return $node;
}

PHP Caller PHP呼叫者

$categories = get_branch(0);

Finally got it going. 终于成功了。

:) :)

you are passing in the $node by reference therefore instead of doing $node[$key][$row['childid']] = get_children($tmp); 您是通过引用传递$node ,而不是这样做$node[$key][$row['childid']] = get_children($tmp); you should really be doing 你应该真的在做

$value[$row['childid']] = get_children($tmp)

or 要么

$node[$row['childid']] = get_children($temp)

but if you go with the second option you will have to pass in $categories[0] on the first call to get_children (which is what you are doing when you are making the recurring calls) 但是如果使用第二个选项,则必须在第一次调用get_children传递$categories[0] (这是您进行重复调用时的操作)

update: 更新:

ill try and explain the reason for that... 请尝试解释其原因...

as you can see the first entry (0) is not duplicated. 如您所见,第一个条目(0)没有重复。 only after the first recurring call is where your problem starts, the reason for that is because you are passing in the child array by reference therefore the second time around [as a example] when you call get_children the $node var actually already refers to the nested part 仅在第一个重复调用是您的问题开始的地方之后,其原因是因为您是通过引用传递子数组,因此第二次[作为示例]调用get_children$node var实际上已经引用了嵌套部分

array(
   0=>array(
      1=>array(/*this is what $node actually is the second time around*/
         /*when you say $node[$key][$row['childid']] what you are actually saying is assign the value to array[0][1][1][4] = array())*/
      )
   )
);

i hope this helps. 我希望这有帮助。 if i can think of a way to explain it batter ill come back and update... 如果我能想到一种解释它的方法,请回来并更新...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM