'PHP Array Conversion for Interview [duplicate]

I have an interview coming up and a previous interviewee posted that this question stumped them:

we have this array:

$input = [
'item/id' => 'my_id',
'item/title' => 'my_title',
'item/group1/val1' => 'my_val1',
'item/group1/val2' => 'my_val2',
'summary' => 'xyz',
'item/group1/val3' => 'my_val3',
];

We need to convert it to :

Array (
  [item] => Array (
    [id] => my_id
    [title] => my_title
    [group1] => Array (
      [val1] => my_val1
      [val2] => my_val2
      [val3] => my_val3
    )
  )
  [summary] => xyz
)

This is using PHP. I know that the answer is:

$input = [
  'item/id' => 'my_id',
  'item/title' => 'my_title',
  'item/group1/val1' => 'my_val1',
  'item/group1/val2' => 'my_val2',
  'summary' => 'xyz',
  'item/group1/val3' => 'my_val3',
];
$result = [];

foreach ($input as $k => $val) {
  $tags = explode('/', $k);
  $parent = [];

  foreach ($tags as $key => $tag) {
    $parentTag = &$result;
      foreach ($parent as $level) {
        $parentTag = &$parentTag[$level];
      }

    if (!isset($parentTag[$tag]) && $key < count($tags) - 1) {
      $parentTag[$tag] = [];
      $parent[] = $tag;

    } elseif (isset($parentTag[$tag])) {
      $parent[] = $tag;
      continue;
    } else {
      $parentTag[$tag] = $val;
    }
  }
}

But I'm getting caught up in some of the reference variables and how it's all working. If someone could walk me through what the solution code is doing I'd really appreciate it. Thanks!

php


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source