views:

81

answers:

2

I have below multidimentional array

$testarray=Array
(
    1 => Array
        (
            0 => 'A',
            1 => 'B'
        ),

    2 => Array
        (
            0 => 'A',
            1 => 'C'
        ),

    3 => Array
        (
            0 => 'A',
            1 => 'C',
            2 => 'D'
        ),

    4 => Array
        (
            0 => 'A',
            1 => 'C',
            2 => 'E'
        ),
   5 => Array
        (
            0 => 'X',
            1 => 'Y'
        ),

    6 => Array
        (
            0 => 'X',
            1 => 'Y',
            2 => 'Z'
        ),

    7 => Array
        (
            0 => 'X',
            1 => 'Y',
            2 => 'ZZ'
        ),

    8 => Array
        (
            0 => 'P',
            1 => 'Q'
        ),

    9 => Array
        (
            0 => 'P',
            1 => 'Q',
            2 => 'R'
        ),

    10 => Array
        (
            0 => 'P',
            1 => 'Q',
            2 => 'R',
            3 => 'S'
        )
);

I need to generate below array using $testarray (aultidimentional array):

array(A=array(B, C=array(D,E)), 
 X=array(Y=>array(Z,ZZ)), 
 P=array(Q=>array(R=>array(S))
A: 

At least in the version of PHP I use you can do something like

$testArray = Array(
    1 => Array(
        'A'=> Array(
              //Value of A here
         )
         'B' => Array(
              //Value of B here
          )
  );

To access them you can write

$testArray[1]['A'];

If you can change the value of $testArray this should help.

Belinda
A: 

This should work. Any refinements (and explanations) would be appreciated.

foreach( $testarray as $values ) {
    $depth = count($values);
    $ref =& $array;

    for( $i=0; $i<$depth; $i++ ) {
        if( $i == $depth-1 ) {
            $ref[] = $values[$i];
        }
        else {
            if( !is_array( $ref ) || !array_key_exists( $values[$i], $ref ) ) {
                $ref[$values[$i]] = array();
            }
            if( ( $key = array_search( $values[$i], $ref ) ) !== FALSE ) {
                unset( $ref[$key] );
            }
            $ref =& $ref[$values[$i]];
        }
    }
}

Output:

 array
  'A' => 
    array
      0 => string 'B' (length=1)
      'C' => 
        array
          0 => string 'D' (length=1)
          1 => string 'E' (length=1)
  'X' => 
    array
      'Y' => 
        array
          0 => string 'Z' (length=1)
          1 => string 'ZZ' (length=2)
  'P' => 
    array
      'Q' => 
        array
          'R' => 
            array
              0 => string 'S' (length=1)
Aether