Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
167 views
Welcome To Ask or Share your Answers For Others

1 Answer

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,
  ),
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...