This discussion focuses on retrieving a hierarchical data structure from a database and converting it into a multidimensional array in a single query. The goal is to obtain an array representing the tree structure of the data.
To extract a tree structure from a database, a closure table is commonly employed. A closure table records the relationships between ancestors and descendants within a hierarchy, enabling efficient querying of descendants.
Given the primary key of a node, querying its descendants using SQL can be achieved using the following steps:
The SQL result is then processed in the following manner:
In PHP, using the Zend Framework, the following code demonstrates the process:
// Get taxonomy table instance $tax = new Taxonomy(); // Fetch tree starting at Rodentia (id 180130) to a depth of 2 $tree = $tax->fetchTree(180130, 2); // Dump the array var_export($tree->toArrayDeep());
The output is a multidimensional array representing the tree structure of the data, such as:
array ( 'tsn' => '180130', 'completename' => 'Rodentia', '_parent' => '179925', '_children' => [ // Child rows... ], )
The above is the detailed content of How can I convert database results into a multidimensional array to represent a hierarchical data structure?. For more information, please follow other related articles on the PHP Chinese website!