0

我有一个多维数组,我想将其转换为修改后的预序遍历树:

$data = array(
    "MTGO" => array("Magic Online" => array("MTGO Masters Edition", "MTGO Masters Edition II", "MTGO Masters Edition III", "MTGO Masters Edition IV")),
    "Expansions" => array("Ice Age Cycle" => array("Coldsnap Theme Decks", "Ice Age", "Alliances"), "Theros" => array("Theros")),
    "unclassified" => array("Portal", "Eight Edition")
);

我尝试过遍历嵌套数组或使用迭代器,但我只是没有成功获得正确的界限。

在这里,我有什么要被左约束的,我如何得到正确的?

foreach ($data as $groupname => $group) {
    echo $i.':'.$groupname . '<br/>';
    if (is_array($group)) {
        foreach ($group as $blockname => $block) {
            $i++;
            if (is_array($block)) {
                echo "&nbsp;&nbsp;&nbsp;" .$i.':'. $blockname . '<br/>';
                foreach ($block as $setname) {
                    $i++;
                    echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" .$i.':'. $setname . '<br/>';
                }
            } else {
                echo "&nbsp;&nbsp;&nbsp;" .$i.':'. $block . '<br/>';
            }
        }
    }
    $i++;
}
4

1 回答 1

0

最后,我找到了一个解决方案,满足我的需求,因此它可以深入 3 级,但可以通过一些调整轻松适应递归需求:

class Mptt_object {
    public $lb;
    public $rb;
    public $data;
    public function __construct($name, $lb, $rb = null) {
        $this->data = $name;
        $this->lb = $lb;
        $this->rb = $rb;
    }
}


function getMptt(array $data)
{
    /** @var Mptt_object[] $mptts */
    $mptts = array();

    $i = 0;
    foreach ($data as $firstLevelElementKey => $firstLevelElement) {

        $i++;

        $firstLevelElementMptt = new Mptt_object($firstLevelElementKey, $i);

        foreach ($firstLevelElement as $secondLevelElementKey => $secondLevelElement) {
            if (is_array($secondLevelElement)) {

                $i++;
                $secondLevelElementMptt = new Mptt_object($secondLevelElementKey, $i);

                $thirdLevelElementMptts = array();
                foreach ($secondLevelElement as $thirdLevelElementKey => $thirdLevelElement) {
                    $i++;
                    $thirdLevelElementMptt = new Mptt_object($thirdLevelElement, $i);
                    $i++;
                    $thirdLevelElementMptt->rb = $i;
                    $mptts[] = $thirdLevelElementMptt;
                }
                $i++;
                $secondLevelElementMptt->rb = $i;
                $mptts[] = $secondLevelElementMptt;
                $mptts = array_merge($mptts, $thirdLevelElementMptts);
            } else {
                $i++;
                $secondLevelElementMptt = new Mptt_object($secondLevelElement, $i);
                $i++;
                $secondLevelElementMptt->rb = $i;
                $mptts[] = $secondLevelElementMptt;
            }
        }
        $i++;
        $firstLevelElementMptt->rb = $i;
        $mptts[] = $firstLevelElementMptt;
    }
    return $mptts;
}
于 2014-01-01T12:41:41.490 回答