我在学校有两个功课问题,我已多次查看过它们并没有得到它
我有这个数组
数组[10] [10] [10]
id parent value
1 0 X
2 1 Y
3 1 Z
4 3 A
5 2 B
6 5 C
7 3 D
8 9 E
9 4 F
10 2 G
我想要的是根据父列生成站点地图。
Example
1 must be at the root
2 and 3 must be childs of 1
10 and 5 must be childs of 2
... and so on.
我想如果我能生成类似
的.xml<object id="1" value="X">
<object id="2" value="Y">
<object id="10" value="G">
</object>
<object id="5" value="B">
</object>
... and so on ...
</object>
</object>
和一个数组
array(
id = > 1
array
);
我不知道它的实际外观,也许是这样的
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
第二个问题我将在以后发布。我正在使用PHP,但C ++和C#也可以,因为算法很重要。任何帮助都会被贬低,因为我对此非常好奇!
答案 0 :(得分:1)
我相信你的数组看起来像这样
$list = array();
$list[] = array("id" => 1,"parent" => 0,"value" => "X");
$list[] = array("id" => 2,"parent" => 1,"value" => "Y");
$list[] = array("id" => 3,"parent" => 1,"value" => "Z");
$list[] = array("id" => 4,"parent" => 3,"value" => "A");
$list[] = array("id" => 5,"parent" => 2,"value" => "B");
$list[] = array("id" => 6,"parent" => 5,"value" => "C");
$list[] = array("id" => 7,"parent" => 3,"value" => "D");
$list[] = array("id" => 8,"parent" => 9,"value" => "E");
$list[] = array("id" => 9,"parent" => 4,"value" => "F");
$list[] = array("id" => 10,"parent" => 2,"value" => "G");
你可以尝试
$xml = new SimpleXMLElement("<data />");
startBuild($list, $xml);
header("Content-Type: text/xml");
echo $xml->asXML();
输出
<?xml version="1.0"?>
<data> <object id="1" value="X">
<object id="2" value="Y">
<object id="5" value="B">
<object id="6" value="C" />
</object>
<object id="10" value="G" />
</object>
<object id="3" value="Z">
<object id="4" value="A">
<object id="9" value="F">
<object id="8" value="E" />
</object>
</object>
<object id="7" value="D" />
</object>
</object>
</data>
使用的功能
function startBuild(array $array, SimpleXMLElement $xml, $no = 0) {
$child = hasChildren($array, $no);
if (empty($child))
return "";
foreach ( $child as $value ) {
$xChild = $xml->addChild("object");
$xChild->addAttribute("id", $value['id']);
$xChild->addAttribute("value", $value['value']);
startBuild($array, $xChild, $value['id']);
}
return true;
}
function hasChildren($array, $id) {
return array_filter($array, function ($var) use($id) {
return $var['parent'] == $id;
});
}