Recreate array from flat (where child arrays store index of parent array) to multidimensional?

前端 未结 2 840
Happy的楠姐
Happy的楠姐 2021-01-14 20:53

I am trying to take a flat array and recreate it so that it\'s multidimensional. I\'ve been looking into array_combine and array_merge, but I\'m not sure that either of thos

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-14 21:07

    Ok, I'm making some assumptions here:

    • Each element has only 1 parent, so the parents array will have only 1 tid
    • The array is sorted such that children will appear only after their parents
    • Top-level elmenets will have parent = 0

    Given that, try this code:

    $original = array ( ... your original array ... );
    $nested = array ();
    
    $n = count($original);
    for ($i = 0; $i < $n; ++$i)
    {
        $nested[$original[$i]->tid] = $original[$i];
        $nested[$original[$i]->tid]->children = array ();
    }
    
    while ($n-- && $current = $original[$n])
        if ($current->parents[0] != 0 && $current->parents[0] != $current->tid)
        {
            $nested[$current->parents[0]]->children[] = $current;
            unset ($nested[$current->tid]);
        }
    

提交回复
热议问题