【问题标题】:PHP Recursion with Associative Array (Menu structure)带有关联数组的 PHP 递归(菜单结构)
【发布时间】:2013-02-17 10:14:17
【问题描述】:

我今天一直在用头撞墙。我有一个 mysql 表,其中包含具有递归父/子关系的菜单项列表。我需要创建一个与之匹配的关联数组。

这是我的代码,下面是我的问题的解释。

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 代码

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;
}

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

上面的函数是从我的主脚本中调用的,如下:

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

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

我的问题。

我的问题是返回数组的结构不是我想要的。

上面的代码返回:

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

我想要的是:

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

空数组表示没有孩子。

我不知道如何摆脱关键值的双重影响。 :(

如果有人能提供帮助,将不胜感激。

干杯, 打盹

【问题讨论】:

    标签: php arrays recursion associative


    【解决方案1】:

    稍微改变方法解决了我的问题。我没有通过引用传递 $categories 数组,而是传递父菜单项的 ID 并返回数组。

    下面的代码使用与我的 OP 中给出的相同的 SQL 数据和 SQL 访问器函数 get_db_children($parentid)。我确信这可以改进,但至少我得到了我的结果。

    @Josh,谢谢您的意见。

    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 调用者

    $categories = get_branch(0);
    

    终于搞定了。

    :)

    【讨论】:

    • 如果您选择更改代码,我会说再进一步,将其用于一个查询。循环执行树逻辑
    【解决方案2】:

    你是通过引用传递$node,因此你应该这样做而不是$node[$key][$row['childid']] = get_children($tmp);

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

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

    但如果您选择第二个选项,则必须在第一次调用 get_children 时传入 $categories[0](这是您在进行重复调用时所做的)

    更新:

    我会试着解释原因......

    如您所见,第一个条目 (0) 没有重复。只有在第一次重复调用之后才是您的问题开始的地方,原因是您通过引用传递子数组,因此第二次 [例如] 当您调用 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())*/
          )
       )
    );
    

    我希望这会有所帮助。如果我能想出一个办法来解释它,面糊生病回来更新......

    【讨论】:

    • 这是PHP的东西,与sql无关。 order by 仅确保顺序并且不会将行加倍。 :(
    • "where parentid=$parentid" 确保返回的数据集仅包含那些具有我正在寻找的 parentid 的条目。因此,按 parentid 分组无论如何都没有效果。
    • 我认为问题出在 get_children() 函数中:" $node[$key][$row['childid']]= get_children($tmp);"
    • 正确,您只需从该行中取出 $key 部分,因为您已经在引用子数组,因为您正在进行嵌套调用。我会尝试更新我的答案来解释那个击球手
    • thnx 4 花时间,但我无法让您的建议发挥作用。我已经尝试过第二种方法,除了我不知道如何通过$categories[0] 之外的任何其他方式。第一种方法:$value[$row['childid']] 引入了一个新的 var $value... 这是一个孤儿。如果你愿意,请详细说明。感谢 var_dump 的提醒 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 2014-07-17
    • 2010-10-31
    • 1970-01-01
    • 2013-04-13
    • 2017-03-25
    • 1970-01-01
    相关资源
    最近更新 更多