根据父ID从四个数组创建多维数组

时间:2017-06-12 20:11:20

标签: php arrays multidimensional-array

来自这四个阵列:

$root = (FORD, FIAT, GM, KIA, FERRARI);  
$parentIsFiat = (Panda, Punto, Tipo);  
$parentIsPanda = (1, 13, 16, 20);  
$parentIs13 = (Red, Blue, White);  

如何创建一个多维数组来给我这个:

FORD  
FIAT  
--Panda  
----1  
----13  
------Red  
------Blue  
------White  
----16  
----20  
--Punto  
--Tipo       
GM  
KIA  
FERRARI

背景:我网站上的当前菜单包含HTML中网站上的每个链接。我想只有实际可见的菜单项的HTML。目前我得到了路径中的每个项目(FIAT> Panda> 13),并且它的兄弟姐妹的代码与此类似:

$categoryPath = \XLite\Core\Database::getRepo('\XLite\Model\Category')->getCategoryPath($this->getCategoryId());  
foreach ($categoryPath as $category) {
    $currentCatID = $category->getID();
    $currentCatSiblings = $category->getSiblings(true);
    foreach ($currentCatSiblings as $sibling) {
        $menuItems[$currentCatID][] = $sibling->getName(); // the four arrays above
    }
}

每个数组都有父ID作为键,所以我可以在正确的位置“附加”它,但我不知道如何从我现有的四个数组构建数组。

2 个答案:

答案 0 :(得分:2)

您可以引入一个临时$parent变量,该变量将引用树中必须插入兄弟姐妹的位置,并将$parent引用进一步向下移动到树的下一代“兄弟姐妹” :

$tree = [];
$parent = &$tree; // Use `= &` to reference the same location
foreach ($categoryPath as $category) {
    $currentCatID = $category->getID();
    $currentCatSiblings = $category->getSiblings(true);
    foreach ($currentCatSiblings as $sibling) {
        $parent[] = [ "name" => $sibling->getName() ];
        if ($sibling->getID() === $currentCatID) $index = count($parent) - 1;
    }
    $parent[$index]["children"] = [];
    $parent = &$parent[$index]["children"]; // Use `= &` to reference the deeper location
}

最后$tree将包含嵌套数组。它将有“子”键来存储嵌套结构,如下所示:

[
  [ "name" => "Ford" ],
  [
    "name" => "Fiat",
    "children" => [
      [
        "name" => "Panda",
        "children" => [
          [ "name" => "1" ],
          [
            "name" => "13",
            "children" => [
              [ "name" => "Red" ],
              [
                "name" => "Blue",
                "children" => [],
              ],
              [ "name" => "White" ],
            ],
          ],
          [ "name" => "16" ],
          [ "name" => "20" ],
        ],
      ],
      [ "name" => "Punto" ],
      [ "name" => "Tipo"  ],
    ],
  ],
  [ "name" => "GM" ],
  [ "name" => "Kia" ],
  [ "name" => "Ferrari" ],
]

或者,如果您希望将名称用作关联数组中的键,则:

$tree = [];
$parent = &$tree; // Use `= &` to reference the same location
foreach ($categoryPath as $category) {
    $currentCatID = $category->getID();
    $currentCatSiblings = $category->getSiblings(true);
    foreach ($currentCatSiblings as $sibling) {
        $parent[$sibling->getName()] = [];
    }
    $parent = &$parent[$category->getName()]; // Use `= &` to reference the deeper location
}

结果:

[
  "Ford" => [],
  "Fiat" => [
    "Panda" => [
      "1" => [],
      "13" => [
        "Red" => [],
        "Blue" => [],
        "White" => []
      ],
      "16" => [],
      "20" => []
    ],
    "Punto" => [],
    "Tipo" => []
  ],
  "GM" => [],
  "Kia" => [],
  "Ferrari" => []
]

答案 1 :(得分:0)

$root = ["FORD", "FIAT", "GM", "KIA", "FERRARI"];
$parentIsFiat = ["Panda", "Punto", "Tipo"];
$parentIsPanda = [1, 13, 16, 20];
$parentIs13 = ["Red", "Blue", "White"];

$desiredOutput = [];

foreach($root as $make){
    $desiredOutput[$make] = [];
}

foreach($parentIsFiat as $model){
    $desiredOutput["FIAT"][$model] = [];
}

foreach($parentIsPanda as $year){
    $desiredOutput["FIAT"]["Panda"][$year] = [];
}

foreach($parentIs13 as $color){
    $desiredOutput["FIAT"]["Panda"][13][$color] = [];
}


var_dump($desiredOutput);

收率:

array(5) {
  ["FORD"]=>
  array(0) {
  }
  ["FIAT"]=>
  array(3) {
    ["Panda"]=>
    array(4) {
      [1]=>
      array(0) {
      }
      [13]=>
      array(3) {
        ["Red"]=>
        array(0) {
        }
        ["Blue"]=>
        array(0) {
        }
        ["White"]=>
        array(0) {
        }
      }
      [16]=>
      array(0) {
      }
      [20]=>
      array(0) {
      }
    }
    ["Punto"]=>
    array(0) {
    }
    ["Tipo"]=>
    array(0) {
    }
  }
  ["GM"]=>
  array(0) {
  }
  ["KIA"]=>
  array(0) {
  }
  ["FERRARI"]=>
  array(0) {
  }
}

要记住的关键是PHP中的所有数组更像是其他语言中的“字典”或“哈希集”类型。 PHP没有“数组”,因为其他语言(Java,C,Javascript,...)拥有它们。如果你想要一个“数组”所以你可以使用像echo $myStuff[3];这样的语法,那么你只需创建一个PHP数组(一个/ k / a“字典”),其中每个键都是一个连续的整数。

在任何数组中查看引擎的示例:

$anyArray = getAnyArray();
foreach($anyArray as $key=>$value){
    echo($key . ":" . $value . "<br>");
}