0

我有两个学校的家庭作业问题,我看了好几遍都没有弄明白

我有这个数组

数组[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.

我想如果我能生成一个像

<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# 也可以,因为算法很重要。任何帮助都将不胜感激,因为我对此非常好奇!

4

1 回答 1

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;
    });
}
于 2012-10-10T19:20:28.820 回答