Search code examples
phparraysrecursionmultidimensional-arrayflatten

Flatten multidimensional array to 3 levels preserving the first level keys


I have a nested multidimensional array like this:

$array = [
    1 => [
        [
            ['catName' => 'Villes', 'catUrl' => 'villes', 'parent' => 151],
            [
                ['catName' => 'Administratif', 'catUrl' => 'territoire', 'parent' => 37],
                [
                    ['catName' => 'Gegraphie', 'catUrl' => 'geographie', 'parent' => 0]
                ]
            ]
        ]
    ]
];

I would like to flatten it to a simpler structure, like this:

array (
  1 => 
  array (
    0 => 
    array (
      'catName' => 'Villes',
      'catUrl' => 'villes',
      'parent' => 151,
    ),
    1 => 
    array (
      'catName' => 'Administratif',
      'catUrl' => 'territoire',
      'parent' => 37,
    ),
    2 => 
    array (
      'catName' => 'Gegraphie',
      'catUrl' => 'geographie',
      'parent' => 0,
    ),
  ),
)

I suppose it would work with some recursive function, but my skills in there are not my best. How can I accomplish this?


Solution

  • It's not pretty, but it works:

    $deeparray = array();  // the really nested array goes here
    $flattened = array();
    
    function flatten($item,$key)
    {
      global $flattened;
      if ( $key == 'catName' || $key == 'catUrl' || $key == 'parent' )
      {
        if ( sizeof( $flattened) == 0 )
        {  $flattened[] = array( $key=>$item );  }
        else
        {
          $last = array_pop($flattened);
          if ( array_key_exists($key,$last) )
          {
            $flattened[] = $last;
            $flattened[] = array( $key=>$item );
          }
          else
          {
            $last[ $key ] = $item;
            $flattened[] = $last;
          }
        }
      }
    }
    
    
    
    array_walk_recursive($deeparray,'flatten',$flattened);
    
    $flattened = array($flattened);