【问题标题】:Turning key-value pairs into a nested array [duplicate]将键值对转换为嵌套数组
【发布时间】:2015-05-17 23:00:34
【问题描述】:

我正在尝试编写一个函数,该函数将基于以这种方式定义的元素数组构建一个树结构数组:

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

所以每个元素都有一个定义的父元素,每个元素都有一个唯一的名称。

基于此,这是我的数组:

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

我需要一个返回这个结果的函数:

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

这是我能得到的最接近的:http://3v4l.org/OGoXa 如您所见,什切青在“世界”中,而不是在世界 => 欧洲 => 波兰 => 什切青

【问题讨论】:

  • 我改写了标题以使用更自然的术语并更具体,并修复了所有那些麻烦的弯引号。

标签: php arrays multidimensional-array


【解决方案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);

【讨论】:

  • 哇,这太棒了,知道为什么“柏林”不在“德国”中,而“Gumience”不在“什切青”中吗? 3v4l.org/RFTPS
  • 为我工作。我正在使用 PHP 5.6.2。如果您使用的是以前版本的 PHP,则可能存在错误。
猜你喜欢
  • 2017-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-09
  • 2017-03-27
  • 2015-03-26
  • 2019-01-31
相关资源
最近更新 更多