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

前端 未结 2 878
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:12

    First off, what you are showing is not an multidimensional array, but an array of StdClass objects.

    If it's alright with you to make them truely arrays then this might do it:

    // initiate result array
    $multiArray = array();
    
    // assume $items is your current array
    foreach( $items as $item )
    {
        // cast StdClass to array
        $objToArray = (array) $item;
    
        // if this item is initiated already merge it with the current item
        $multiArray[ $objToArray[ 'tid' ] ] = isset( $multiArray[ $objToArray[ 'tid' ] ] ) ? $multiArray[ $objToArray[ 'tid' ] ] + $objToArray : $objToArray;
    
        foreach( $objToArray[ 'parents' ] as $parentId )
        {
            // if parents don't exist yet, initiate them
            if( !isset( $multiArray[ $parentId ] ) )
            {
                $multiArray[ $parentId ] = array(
                    'children' => array()
                );
            }
    
            // add this item to the parents children collection by reference (for efficiency)
            $multiArray[ $parentId ][ 'children' ][ $objToArray[ 'tid' ] ] = &$multiArray[ $objToArray[ 'tid' ] ];
        }
    }
    

    With this you can easily find items by id with:

    $item = $multiArray[ $someId ];
    

    And to get a child:

    $child = $item[ 'children' ][ $someChildId ];
    

    Or all children:

    $children = $item[ 'children' ];
    

    EDIT
    Ok, I've tested it now, and it seems to work fine after adding some missing semicolons.

提交回复
热议问题