0

Based on data from an XML-file stored in the variable $Xml I want to create a new array with custom properties.

I did start with a foreach-loop:

foreach($Xml->Sequences->Sequence as $var=>$value) {

    $MyObject[] = array(
        "title"  => $value->SequenceName->__toString(),
        "folder" => true
    );

}

That's OK. The result looks like this:

Array
(
    [0] => Array
        (
            [title] => Folder1
            [folder] => 1
        )

    [1] => Array
        (
            [title] => Folder2
            [folder] => 1
        )
)

The variable $Xml also contains sub-properties and I need to insert them in my new array.
The desired result would be:

Array
(
    [0] => Array
        (
            [title] => Folder1
            [folder] => 1
            [children] => Array
                (
                    [0] => Array
                        (
                            [title] => Package1
                        )

                )

        )
)

I don't know how to get this result!
In my opinion, I need to start another foreach-loop to get the sub-properties and store them in the array for the current element in the loop. I did use a code like this, but ofc a new node is created and it is not stored in the parent-node.

foreach($Xml->Sequences->Sequence as $var=>$value) {

    $MyObject[] = array(
        "title"  => $value->SequenceName->__toString(),
        "folder" => true,
    );

    foreach ($value->SequencePackages->Package as $a=>$b){
        $MyObject[] = array(
            "children" => array(array(
                "title" => $b->PackageFolder->__toString(),
            ))
        );
    }

}

I believe the solution is easy, but I can't figure out alone ...

Thank you for your support.

4

3 回答 3

0

你需要做一些这样的事情。您需要使用父数组中的键并插入新值子 foreach($Xml->Sequences->Sequence as $var=>$value) {

$MyObject[] = array(
    "title"  => $value->SequenceName->__toString(),
    "folder" => true,
);

foreach ($value->SequencePackages->Package as $a=>$b){
    $MyObject[‘children’] = array(
            "title" => $b->PackageFolder->__toString(),

    );
}

}
于 2019-12-14T07:33:16.127 回答
0

用于创建数组的父循环的用户索引。

$MyObject[$var] = array(
        "title"  => $value->SequenceName->__toString(),
        "folder" => true
    );

$MyObject[$var]['children'][] = array(array(
                "title" => $b->PackageFolder->__toString(),
            ));
于 2019-12-14T07:40:39.433 回答
0

建立新的数组数据并将其添加到最后而不是每个阶段的主数组中会更容易......

$MyObject = [];
foreach($Xml->Sequences->Sequence as $var=>$value) {
    $newObject =array(
        "title"  => $value->SequenceName->__toString(),
        "folder" => true,
    );

    foreach ($value->SequencePackages->Package as $a=>$b){
        $newObject["children"][] = ["title" => $b->PackageFolder->__toString()];
    }
    $MyObject[] = $newObject;
}
于 2019-12-14T07:42:46.893 回答