Attenzione! Stai navigando il vecchio sito
Vai alla nuova homepage »
Impegni permettendo sto rinnovando il sito. Le informazioni che trovi in questo vecchio sito sono obsolete e mano a mano verranno rimpiazzate.

PHP - Convert flat array to nested

Scritto da Marco Panichi il Aggiornato il
php convert flat array to nested

Sometimes we have a two-dimensional array where are defined father-child relations.

This is particulary true when the array come from a table selected from a database.

I’ve created this function to convert flat array to nested array because I needed this kind of structure for a project of mine.

Example data

Imagine that we have an array like this one:

$data = array(
	'1' => array( 'label' => "A", 'father' => '' ),
	'2' => array( 'label' => "B", 'father' => '' ),
	'3' => array( 'label' => "C", 'father' => '' ),
	'4' => array( 'label' => "D", 'father' => '' ),
	'5' => array( 'label' => "one", 'father' => '1' ),
	'6' => array( 'label' => "two", 'father' => '1' ),
	'7' => array( 'label' => "three", 'father' => '1' ),
	'8' => array( 'label' => "node 1", 'father' => '2' ),
	'9' => array( 'label' => "node 2", 'father' => '2' ),
	'10' => array( 'label' => "node 3", 'father' => '2' ),
	'11' => array( 'label' => "I", 'father' => '9' ),
	'12' => array( 'label' => "II", 'father' => '9' ),
	'13' => array( 'label' => "III", 'father' => '9' ),
	'14' => array( 'label' => "IV", 'father' => '9' ),
	'15' => array( 'label' => "V", 'father' => '9' ),
);

As you can see this is the typical situation you can encounter after extracting a table from a database. The keys of the array are the taken from the id column of the database and the values of each array rapresent other columns.

The function to convert flat array to nested

After tested many solutions, I’ve found out this one:

function array_totree( &$a, $parent_key, $children_key='children' )
{
	$orphans = true; $i;
	while( $orphans )
	{
		$orphans = false;
		foreach( $a as $k=>$v )
		{
			// is there $a[$k] sons?
			$sons = false;
			foreach( $a as $x=>$y )
			{
				if( $y[$parent_key]!=false and $y[$parent_key]==$k )
				{
					$sons=true; $orphans=true; break;
				}
			}
			
			// $a[$k] is a son, without children, so i can move it
			if( !$sons and $v[$parent_key]!=false )
			{
				$a[$v[$parent_key]][$children_key][$k] = $v;
				unset( $a[$k] );
			}
		}
	}
}

 

Arguments

This function accepts three arguments:

  1. ARRAY $array

    The input array that we want to order. The array is passed by reference

  2. STRING $parent_key

    The associative key used to define the father id of a node inside the node itself

  3. STRING $children_key

    The associative key that will be created by the function and that will be rapresent the children of the new multi dimensional array

Return

The function returns nothing.

Usage

Let’s assume we are using the $data  array defined above. So we can apply the function that way:

array_totree( $data, 'father', 'children' );

The output

Now the $data array looks like:

  • A
    • one
    • two
    • three
  • B
    • node 1
    • node 3
    • node 2
      • I
      • II
      • III
      • IV
      • V
  • C
  • D

The complete script

You can download the whole script (that include the example also) just clicking the button below.

Download the Function + Example

Hope this helps

I hope you have used found useful my solution.

If you have encountered some problems, please let me know.

If you have a smarter solution to convert flat array to nested please add a comment below.

Bye!

Commenti

Informativa
Noi e terze parti usiamo strumenti di tracciamento (cookie e tecnologie affini) per finalità tecniche e, con il tuo consenso, anche per altre finalità specificate nella Cookie Policy. In qualsiasi momento puoi liberamente prestare, revocare o rifiutare tale consenso. Per ulteriori informazioni vedi: Privacy Policy - Cookie Policy
X
Personalizza il tuo consenso
Da qui puoi esprimere le tue preferenze rispetto i cookie e le tecnologie che usiamo per le varie finalità. Ricordati che in qualsiasi momento puoi liberamente modificare queste preferenze. Per ulteriori informazioni vedi: Privacy Policy - Cookie Policy
Strumenti di tracciamento di terze parti INFO
Cookie o strumenti di tracciamento gestiti da terze parti. Essi sono strettamente necessari per garantire il funzionamento e la fornitura del servizio richiesto dall'utente e quindi non richiedono il suo consenso.
Miglioramento dell'Esperienza INFO
Cookie utili per fornire un'esperienza utente migliore e personalizzata, tramite la gestione delle impostazioni personali e l'interazione con piattaforme di terzi e network.
Misurazione INFO
Strumenti per misurare il traffico e analizzare il comportamento degli utenti con l'obiettivo di migliorare il servizio.
Targeting e Pubblicità INFO
Strumenti per fornire contenuti commerciali personalizzati in base al comportamento dell'utente e per gestire, diffondere e tracciare annunci pubblicitari.
X