我正在尝试从表中检索分层数据,但未能成功。该表(目前)具有以下列:ifc_key、ifc_name、ifc_parent。不使用 ifc_key。 (主键,但不用于此功能。
目的是得到一个数组。每个元素都是一个“父”接口(interface)。 (所以所有这些根元素都是没有设置 ifc_parent 的 ifc_name 值(如果设置则等于 ifc_name)。
考虑以下布局(演示):
ifc_key | ifc_name | ifc_parent
0 | parent_ifc |
1 | a0a | parent_ifc
2 | a0b | parent_ifc
3 | b0a | vif1
4 | b0b | vif1
5 | vif1 | a0a
所以我正在寻找的数组是:
Array
(
[parent_ifc] => Array
(
[a0a] => Array
(
[vif1] => Array
(
[0] => b0a
[1] => b0b
)
)
[a0b] =>
)
)
我想出的功能在这一段下面。我想创建一个递归函数,它会在找到 child 时自行调用,但问题是在第一次调用此方法时没有选择任何 child 。 ( parent 为空的 parent 自己)。所以我只让 parent 回来,但没有 child (可能还有他们的 child 等——理论上这可以是不确定的)。
public static function getByFilerOrganisedChildren($filer_id, $parent = '')
{
$table = new Filer_Interface_Table();
$where[] = $table->getAdapter()->quoteInto('ifc_system_id = ?', $filer_id);
$where[] = $table->getAdapter()->quoteInto('ifc_parent = ?', $parent);
$rows = $table->fetchAll($where, 'ifc_parent ASC');
foreach ($rows as $row) {
if ($row->ifc_parent == '') $data[] = $row->ifc_name;
else {
$data[$row->ifc_parent][] = $row->ifc_name;
self::getByFilerOrganisedChildren($filer_id, $row->ifc_parent);
}
}
return (isset($data) ? $data : false);
}
最佳答案
在您的方法之前您没有引用 ifc_system_id
列,因此我认为这与问题不直接相关。此外,您指定为理想的输出实际上是不一致的。
您缺少的关键似乎是使用与子记录相关的数据调用递归函数 - 在这种情况下,ifc_name
而不是 ifc_parent
.
public function getByFilerOrganisedChildren($filer_id, $parent = '')
{
$table = new Filer_Interface_Table();
$where[] = $table->getAdapter()->quoteInto('ifc_system_id = ?', $filer_id);
$where[] = $table->getAdapter()->quoteInto('ifc_parent = ?', $parent);
$rows = $table->fetchAll($where, 'ifc_parent ASC');
$data = array();
foreach ($rows as $row) {
$data[$row->ifc_name] = $this->getByFilerOrganisedChildren($row->ifc_name);
}
return (! empty($data) ? $data : false);
}
关于用于从平面表(Zend Framework)检索分层数据的 PHP 递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2372815/