Converting Database Results into Arrays
To transform database results into an array while maintaining a hierarchical structure, consider employing a "Closure Table" approach. Here's how it works:
-
Create a Closure Table: Establish a table that tracks hierarchical relationships, capturing the parent-child relationships between the data.
-
Execute a SQL Query: Using an appropriate SQL statement, fetch the necessary data and parent relationships from the closure table.
-
Recursive Data Processing: Perform recursive processing on the resultset. For each row, identify its parent and assign it to the "children" property of its parent.
-
Convert to Array: The recursive processing enables the construction of a tree-like structure. Use the "toArrayDeep()" method to convert this structure into a plain array.
- Example:
// Fetch tree starting at Rodentia (id 180130), to a depth of 2
$tree = $tax->fetchTree(180130, 2);
// Dump out the array
var_export($tree->toArrayDeep());
Copy after login
This technique effectively organizes your data in a hierarchical manner, allowing for easy navigation and manipulation.
The above is the detailed content of How can I transform hierarchical database results into an array?. For more information, please follow other related articles on the PHP Chinese website!