-1

I'm trying to write a function which will build a tree-structured array based on array of elements defined this way:

array(
  'child1' => 'parent',
  'child2' => 'parent',
)

so each element has a defined parent and each element has a unique name.

Based on that, here is my array:

myArray(
  'Europe' => 'World',
  'Africa' => 'World',
  'UK' => 'Europe',
  'France' => 'Europe',
  'London' => 'UK',
)

And I need a function which will return this result:

World => Array (
    Europe=> Array (
        UK=>Array(
            London=>Array()
        ), 
        France=>Array()
    ), 
    Africa=>Array()
)

This is the closest I could get: http://3v4l.org/OGoXa as you can see, Szczecin is in "World", not in World => Europe => Poland => Szczecin

zee
  • 359
  • 3
  • 16
  • 1
    I rewrote the title to use more natural terminology and be specific, and fixed all those troublesome curly quotes. – Nathan Tuggy Mar 15 '15 at 22:12

1 Answers1

1
$myArray = array(
  'Europe' => 'World',
  'Africa' => 'World',
  'UK' => 'Europe',
  'France' => 'Europe',
  'London' => 'UK',
);

$x = new SimpleXMLElement ("<root/>");
foreach ($myArray as $child => $parent)
{
  if (!$x->xpath ("//$parent"))
  {
    $x->addChild($parent);
  }
  $x->xpath ("//$parent")[0]->addChild($child);
}
$json = json_encode($x);
$array = json_decode($json,TRUE);
var_dump ($array);
akond
  • 15,865
  • 4
  • 35
  • 55
  • Wow, this rocks, any idea why 'Berlin' is not in 'Germany' and 'Gumience' in 'Szczecin'? http://3v4l.org/RFTPS – zee Mar 15 '15 at 23:50
  • Works for me. I'm using PHP 5.6.2. If you're using some previous version of PHP, there is probably a bug. – akond Mar 16 '15 at 16:50