我想根据父ID获取子用户ID。我找到了解决办法 如何在php中计算每个级别的15级深度的成员 尝试过的答案 https://stackoverflow.com/a/45535568/23864372 但出现一些错误。
我创建了一个类 -
<?php
Class Team extends Database {
private $dbConnection;
function __construct($db)
{
$this->dbConnection = $db;
}
public function getDownline($id, $depth=5) {
$stack = array($id);
for($i=1; $i<=$depth; $i++) {
// create an array of levels, each holding an array of child ids for that level
$stack[$i] = $this->getChildren($stack[$i-1]);
}
return $stack;
}
public function countLevel($level) {
// expects an array of child ids
settype($level, 'array');
return sizeof($level);
}
private function getChildren($parent_ids = array()) {
$result = array();
$placeholders = str_repeat('?,', count($parent_ids) - 1). '?';
$sql="select id from users where pid in ($placeholders)";
$stmt=$this->dbConnection->prepare($sql);
$stmt->execute(array($parent_ids));
while($row=$stmt->fetch()) {
$results[] = $row->id;
}
return $results;
}
}
我正在使用这样的课程-
$id = 1;
$depth = 2; // get the counts of his downline, only 2 deep.
$downline_array = $getTeam->getDownline($id, $depth=2);
我收到错误 - 排队
$placeholders = str_repeat('?,', count($parent_ids) - 1). '?';
致命错误:未捕获类型错误:count():参数 #1 ($value) 必须是 类型为 Countable|array,int 给出于
第二个
警告:PDOStatement::execute():SQLSTATE[HY093]:无效参数 number:绑定变量的数量与中的标记数量不匹配 线
$sql="select id from users where pid in ($placeholders)";
$stmt=$this->dbConnection->prepare($sql);
我想获取5个级别的子用户ID。 PHP 版本 8.1
数据库表
superheroes
-----------
id parent_id name
1 0 Steven Rogers
2 1 Bruce Banner
3 1 Wally West
4 2 Peter Parker
5 2 Jay Garrick
6 4 Barry Allen
7 4 Reed Richards
有几个小问题:
$result = array();
是一个错字,应该是$results = array();
$stack = array($id);
需要是 $stack = array([$id]);
,因为当您编写 $stack[$i-1]
时,它会从该数组中取出一个值,如果没有此更改,则第一次运行代码时,数组中的值只是 1
.$results[] = $row->id;
应该是 $results[] = $row["id"];
,因为您是从数据库中以数组而非对象的形式获取行。这是重写的类:
Class Team extends Database {
private $dbConnection;
function __construct($db)
{
$this->dbConnection = $db;
}
public function getDownline($id, $depth=5) {
$stack = array([$id]);
for($i=1; $i<=$depth; $i++) {
// create an array of levels, each holding an array of child ids for that level
$stack[$i] = $this->getChildren($stack[$i-1]);
}
return $stack;
}
public function countLevel($level) {
// expects an array of child ids
settype($level, 'array');
return sizeof($level);
}
private function getChildren($parent_ids = array()) {
$results = array();
$placeholders = str_repeat('?,', count($parent_ids) - 1). '?';
$sql="select id from users where pid in ($placeholders)";
$stmt=$this->dbConnection->prepare($sql);
$stmt->execute($parent_ids);
while($row=$stmt->fetch()) {
$results[] = $row["id"];
}
return $results;
}
}