如何遍历结果集直至最后层级,获取产品分类末级节点?
Hey there! Let's work through this problem together. From your description, you need to crawl a product category hierarchy until you reach the leaf nodes—which are only identifiable by the linetype field. You're thinking of using a while loop but confused about handling the handoff between stockCode (child IDs) and ParentStockCode (next round's parent IDs). Here's a clear, actionable solution:
Core Logic Overview
The idea is to iterate through the hierarchy in layers:
- Start with your initial set of parent category IDs.
- Fetch all child categories for the current parent IDs.
- Split these children into two groups: leaf nodes (keep them) and non-leaf nodes (use their
stockCodeas the next batch of parent IDs). - Repeat until there are no more non-leaf nodes to process.
Step-by-Step Implementation Example
Let's use Python for this example (the logic translates easily to other languages like Java, JavaScript, etc.):
def collect_leaf_categories(initial_parent_ids): # Initialize with your starting parent IDs current_parents = initial_parent_ids.copy() all_leaf_nodes = [] while current_parents: # 1. Fetch subcategories using the current parent IDs as ParentStockCode sub_categories = your_api_call_to_get_subcategories(current_parents) # 2. Separate leaves and non-leaves # Adjust the linetype check to match your actual leaf identifier leaf_nodes = [cat for cat in sub_categories if cat["linetype"] == "leaf"] non_leaf_ids = [cat["stockCode"] for cat in sub_categories if cat["linetype"] != "leaf"] # 3. Add leaves to our final collection all_leaf_nodes.extend(leaf_nodes) # 4. Update parents for next iteration: use non-leaf stockCodes as new ParentStockCode current_parents = non_leaf_ids return all_leaf_nodes
Key Details to Note:
your_api_call_to_get_subcategories: Replace this with your actual API/function that takes a list ofParentStockCodevalues and returns the corresponding subcategories.linetypeCheck: Make sure the condition matches your system's actual leaf node identifier—this could be a boolean (is_leaf: True), a specific string like"terminal", etc.- Avoiding Dead Loops: If your category hierarchy has circular references (e.g., Category A's parent is B, B's parent is A), add a set to track processed IDs and skip any that have already been handled.
- Empty Batches: If a batch of parent IDs returns no subcategories,
non_leaf_idswill be empty, and the loop will terminate gracefully.
Clarifying Your Confusion
Your question mentions confusion about using the returned stockCode collection as ParentStockCode content—this is exactly what the line current_parents = non_leaf_ids does. Every iteration, we take the stockCode of non-leaf child categories and pass them as the ParentStockCode parameter for the next API call. This creates the chain of traversal from top-level categories down to the leaves.
内容的提问来源于stack exchange,提问作者Ovic

