views:

56

answers:

1

Hi friends,

I have array as follows

array (A => 1)
array (A => 1, B=>2)
array (A => 1, B=>2, C=>3)
array (A => 1, D=>4)
array (A => 1, E=>5)
array (A => 1, F=>6)
array (A => 1, F=>6, G=>8)
array (A => 1, F=>6, H=>9)
array (X => 11)
array (X => 11, Y=22)
array (X => 11, Z=33)

I need to form array as follows

array(A=>array(B=>2, C=>3, D=>4, E=>5, F=>array(G=>8,H=>9))
  X=>array(Y=>22, Z=>33)
A: 

I think this is what you’re looking for:

$result = array();
foreach ($arrays as $array) {
    $ref = &$result;
    foreach ($array as $key => $val) {
        if (!isset($ref[$key])) {
            $ref[$key] = $val;
        } elseif (!is_array($ref[$key])) {
            $ref[$key] = array();
        }
        $ref = &$ref[$key];
    }
}

Here the keys are interpreted as path segments to walk the array using a reference. If there is no value yet, the value is stored; if there already is a value, it is replaced by an array.

But this is generating a little different result:

array (
  'A' => 
  array (
    'B' => 
    array (
      'C' => 3,
    ),
    'D' => 4,
    'E' => 5,
    'F' => 
    array (
      'G' => 8,
      'H' => 9,
    ),
  ),
  'X' => 
  array (
    'Y' => 22,
    'Z' => 33,
  ),
)
Gumbo
should'nt it be recursive?
Ayaz Alavi
where is A => 1,x=11?
JapanPro
@JapanPro: Where is it in the expected result in the question?
Gumbo
A => 1,x=11 is not require.
Rahul
Gumbo, it should work for multidimentional array. And multidimentional array could be upto 10
Rahul
@user459588: What multidimensional array? Can you give an example of such an array?
Gumbo
array(A=>array(B=>2, C=>3, D=>4, E=>5, F=>array(G=>8,H=>9)) X=>array(Y=>22, Z=>33)
Rahul
See array element F=>array(G=>8, H=>9, k=array(P=>121, Q=>444, R=>array(J=99, L=101))
Rahul
@user459588: That’s what you’re wrote in the question. How does my proposal does not fit this result (apart from that *B* is also an array containing *C*)?
Gumbo
@user459588: Please be more specific. Give examples for input and expected output.
Gumbo
Please check http://stackoverflow.com/questions/3811232/php-multidimentional-array
Rahul