Kyobul Kyobul - 4 months ago 7
PHP Question

How can I transform a multidimensional array to a simpler structure?

I have a nested multidimensional array like this:

Array (
[1] => Array
(
[0] => Array
(
[0] => Array
(
[catName] => Villes
[catUrl] => villes
[parent] => 151
)

[1] => Array
(
[0] => Array
(
[catName] => Administratif
[catUrl] => territoire
[parent] => 37
)

[1] => Array
(
[0] => Array
(
[catName] => Gegraphie
[catUrl] => geographie
[parent] => 0
)

)

)

)
)


I would like to regroup it to simpler level, 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?

Answer

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);
Comments