Home > Software design >  Need array that consists of parent and child relations in PHP
Need array that consists of parent and child relations in PHP

Time:09-29

Hi there I have an array which consists of parent and child relations.

$data = array(
677 => 678
678 => 679
679 => 880
880 => 881
881 => 882
882 => 883
883 => 884);

Here values are main article id and values are those child ids. went this way

$k = [];
foreach($data as $key => $val) {
  $k[$key][$val] = $data[$val];
}

But my result is $k

Array
(
  [677] => Array
  (
    [678] => 679
  )
    [678] => Array
  (
    [679] => 880
  )
    [679] => Array
  (
    [880] => 881
  )
    [880] => Array
  (
    [881] => 882
  )
    [881] => Array
  (
    [882] => 883
  )
    [882] => Array
  (
    [883] => 884
  )
    [883] => Array
  (
    [884] => 
  )
)

But I need something like

677 => [
  678 => [
    679 => [
      880 => [
        881 => [
          882 => [
            883 => [
              884
            ]
          ]
        ]
      ]
    ]
  ]
]

Tried in multiple ways and there is something I am missing and need someones help in solving this. in foreach only remaining array keys should be added as values of some value. Thanks in advance

[
  [677] => [
    [id] => 677
    [child] => [
      [id] => 678
      [child] => [
        [id] => 679
        [child] => [
          [id] => 880
          [child] => [
            [id] => 881
            [child] => [
              [id] => 882
              [child] => [
                [id] => 883
                [child] => 884
              ]
            ]
          ]
        ]
      ]
    ]
  ]
]

CodePudding user response:

So, if the order of your IDs are in fact ordered meaning, parent before child fashion, then you can do the below:

  • We use references to keep track of previous parent array which gives us the ability to edit the current array in place.

  • If the previous key's value matches the current key, it means the current key(which was the previous value) has a child. We use this to decide whether it is going to be an array key or value.

  • For the next iteration, catch hold of the reference of the current child array and repeat the same steps.

Snippet:

<?php

$result = [];
$prev = &$result;

foreach($data as $key => $val){
  $prevKey = $prev[0] ?? -1;
  if($prevKey === $key){
    $prev = [ $key  => [ $val ] ];
  }else{
    $prev[ $key ] = [ $val ];
  }
  
  $prev = &$prev[ $key ];
}

print_r($result);

Online Demo


Update:

Modified with id and child keys' format making the code more concise.

<?php

$result = [];
$prev = &$result;

foreach($data as $key => $val){
  $prev = ['id' => $key, 'child' => []];
  $prev = &$prev['child'];
}

$prev = ['id' => $val, 'child' => [] ];

print_r($result); 

Online Demo

  • Related