You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组按_level与_parent分组并按_id排序的实现需求

Solution for Grouping & Sorting Hierarchical Array by _level, _parent and _id

Hey there! Let's tackle this problem of restructuring your array to group by _level/_parent, sort by _id, and output a structure where each element is keyed by its _id. I'll use PHP for the example since your sample output matches PHP's array syntax.

Step 1: Break Down the Requirements

We need to:

  • Organize elements by their hierarchical level (_level) and parent-child relationship (_parent)
  • Sort elements within each level by _id in ascending order
  • Finalize with an associative array using each item's _id as the key

Step 2: Example Implementation

First, let's assume your original raw array looks like this (adjust to match your actual data):

$originalArray = [
    ["desc" => "sub array", "_id" => 172, "_parent" => 163, "_level" => 2],
    ["desc" => "master array", "_id" => 163, "_parent" => null, "_level" => 1],
    ["desc" => "sub array from 172", "_id" => 167, "_parent" => 172, "_level" => 3],
    ["desc" => "sub array", "_id" => 200, "_parent" => null, "_level" => 1],
];

Now let's build the solution step by step:

// 1. Index all items by their _id for fast parent-child lookups
$indexedById = [];
foreach ($originalArray as $item) {
    $indexedById[$item['_id']] = $item;
}

// 2. Group items by their _level, then sort each level's items by _id
$groupedByLevel = [];
foreach ($indexedById as $item) {
    $level = $item['_level'];
    if (!isset($groupedByLevel[$level])) {
        $groupedByLevel[$level] = [];
    }
    $groupedByLevel[$level][] = $item;
}

// Sort each level's items by _id ascending
foreach ($groupedByLevel as &$levelItems) {
    usort($levelItems, function($a, $b) {
        return $a['_id'] - $b['_id'];
    });
}
unset($levelItems); // Clean up the reference to avoid unexpected behavior

// 3. Recursively build the final array following parent-child chains
$result = [];

// Helper function to add child items recursively
function addChildItems($parentId, $groupedByLevel, $indexedById, &$result) {
    $currentChildLevel = $indexedById[$parentId]['_level'] + 1;
    if (!isset($groupedByLevel[$currentChildLevel])) {
        return; // No children exist at this level
    }
    foreach ($groupedByLevel[$currentChildLevel] as $child) {
        if ($child['_parent'] === $parentId) {
            $result[$child['_id']] = $child;
            addChildItems($child['_id'], $groupedByLevel, $indexedById, $result);
        }
    }
}

// Start with top-level items (_level = 1) and build downwards
foreach ($groupedByLevel[1] as $topLevelItem) {
    $result[$topLevelItem['_id']] = $topLevelItem;
    addChildItems($topLevelItem['_id'], $groupedByLevel, $indexedById, $result);
}

// Print the final structure
print_r($result);

Step 3: Expected Output

Running this code will produce exactly the structure you requested:

Array
(
    [163] => Array
        (
            [desc] => master array
            [_id] => 163
            [_parent] => 
            [_level] => 1
        )

    [172] => Array
        (
            [desc] => sub array
            [_id] => 172
            [_parent] => 163
            [_level] => 2
        )

    [167] => Array
        (
            [desc] => sub array from 172
            [_id] => 167
            [_parent] => 172
            [_level] => 3
        )

    [200] => Array
        (
            [desc] => sub array
            [_id] => 200
            [_parent] => 
            [_level] => 1
        )

)

Key Notes

  • Indexing by _id makes parent-child lookups efficient (O(1) instead of looping through the entire array repeatedly)
  • Sorting each level before processing ensures items are ordered by _id as required
  • The recursive helper function ensures we follow the full parent-child chain, adding nested children in the correct order

内容的提问来源于stack exchange,提问作者BayuRizki IsnaeniHidayatuloh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:25:51