Skip to content
Advertisement

How to mirror an array recursively?

I have a tree from the youngest to the oldest

$demo = [
    'name' => 'name 3',
    'parent' => [
        'name' => 'name 2',
        'parent' => [
            'name' => 'name 1',
            'parent' => null
        ]
    ]
];

I need to mirror it (turn it inside out, if I may say so) to get such a structure

 $mirror = [
            'name' => 'name 1',
            'child' => [
                'name' => 'name 2',
                'child' => [
                    'name' => 'name 3',
                    'child' => null
                ]
            ]
        ];

I’ve been working on this task for quite a long time and I can’t think of an algorithm to do it. What should I do to get the second option while having the first one?

Advertisement

Answer

This function will give you what you are looking for.

It is a recursive function that works its way down to the bottom of your list then progressively rebuilds it from the bottom up.

function mirror(?array $array, array $subArray = []) :array
{   
    // when $array is null, we have reached the final parent and thus the recursion is over
    if ($array === null){
        return $subArray;
    }
    
    $name = $array['name'];
    $parent = $array['parent'];
    
    // this should only be the case for the top layer of the initial array
    if (empty($subArray)) {
        return mirror($parent, [
            'name' => $name,
            'child' => null
        ]);
    }
    
    $subArray = [
        'name' => $name,
        'child' => $subArray
    ];
    
    return mirror($parent, $subArray);
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement