簡體   English   中英

遞歸 PHP 函數中的 concat 樹層次結構

[英]concat tree hierarchie in a recursive PHP function

我有一個包含分層用戶的用戶表。 所以用戶可以有一個父用戶。 我正在嘗試返回某個用戶的所有子用戶 ID 的數組。 我的函數返回“null”。 怎么了?

public function userDownline($userid, $result = array()) {
    $dbconn = $this->DBase();
    $children = $dbconn->GetAll('SELECT id FROM users WHERE parent=' . (int)$userid);
    if(count($children) > 0) {
        foreach($children As $k=>$v) {
            if(!in_array($v['id'], $result)) $result[] = $v['id'];
            $this->userDownline($v['id'], $result);
        }
    } else {
        return $result;
    }
}    

當然它會返回 null,因為你在塊中 if(count($children)) 並且沒有返回。

我認為你必須做這樣的事情:

<?php
public function userDownline($userid, &$result = array())
{
    $dbconn = $this->DBase();
    $children = $dbconn->GetAll('SELECT id FROM users WHERE parent=' . (int)$userid);
    if (count($children) > 0) {
        foreach ($children As $k => $v) {
            if (!in_array($v['id'], $result)) $result[] = $v['id'];
            $this->userDownline($v['id'], $result);
        }
    }
    return $result;
}

我在函數簽名中添加了引用並將返回移出條件塊。

但這確實是完全低效且危險的方式(因為 - 內存不足,嵌套級別過多和其他異常)。

有2種更好的方法:

  1. 使用https://neo4j.com/ - 圖形數據庫 - 最適合您的任務。
  2. 如果您仍然只想使用 Sql DB - 閱讀嵌套集模型http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM