I'm trying to retrieve hierarchical data from a table but am failing to do so. The table has (for now) the following columns: ifc_key, ifc_name, ifc_parent. ifc_key is not used. (primary key, but not used for this function.
The purpose is to get an array. Each element is a "parent" interface. (so all these root elements are ifc_name values that don't have an ifc_parent set (equals ifc_name if set).
Consider the following layout (demo):
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
So the array I'm looking for, generated from a query is:
Array
(
[parent_ifc] => Array
(
[a0a] => Array
(
[vif1] => Array
(
[0] => b0a
[1] => b0b
)
)
[a0b] =>
)
)
The function I came up with is underneath this paragraph. I wanted to created a recursive function, which calls itself upon finding children but the problem is that none of the children are selected upon the first call to this method. (those with empty parent are parents themselves). So I only get the parents back, but none of the children (and possibly their children, etc - this can in theory be indefinite).
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);
}