Recursively loop through multidimensional to create flat array

后端 未结 3 1995
我在风中等你
我在风中等你 2021-01-26 16:36

I have a multidimensional array that looks like this:

$trees = array(
    array(
        \'name\' => \'Parent\',
        \'__children\' => array(
                  


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-26 17:20

    I ended up using something like this, with a lot of inspiration from @Pankrates answer. Thanks a lot.

    $trees = $multidimensionalArray;
    $flat = array();
    $postRepository->flattenRecursive($flat, $trees);
    //$flat is now a flattened version of $multidimensionalArray
    var_dump($flat);
    
    
    public function flattenRecursive(array &$flat, array $nested, $parentPrepend = false)
    {
        foreach( $nested as $item ){
            $flat[] = array(
                'name' => ($parentPrepend) ? $parentPrepend . '/' . $item['name'] : $item['name']
            );
            $prepend = $parentPrepend ? $parentPrepend . '/' . $item['name'] : $item['name'];
            if(isset($item['__children']))
                $this->flattenRecursive($flat, $item['__children'], $prepend);
        }
    }
    

提交回复
热议问题