php从多个数组中创建嵌套数组

时间:2015-06-26 07:45:22

标签: php arrays laravel-5

我想用父树制作一个结构合理的类别,但我似乎无法找到正确的方法来正确地做到这一点。 这是前提: 1个产品有很多类别。 1类可能有父母。

这是我目前拥有的数组(这些数组中的值只是一个例子)

array:4[
  1=> array:2 [
    2 =>2 
    4 => 4
  ]
  2=> array:1[
    3=>3
  ]
  3=> array:1[
    5=>5
  ]
  9=> array:1[
    6=>6
  ]
]

现在我想要这个

array:4[
  1=> array:2 [
    2 => array:1 [
      3=> array:1 [
        5=>5
      ]
    ] 
    4 => 4
  ]
  9=> array:1[
    6=>6
  ]
]

如何在保持数组键的同时将第一个转换为第二个,我想使用键来调用另一个包含所有相关对象和数据的数组 所以我可以得到这个结果: http://www.bootply.com/dFeKoQmgb2

2 个答案:

答案 0 :(得分:0)

如果您尝试以下代码该怎么办?请注意,必须有一个更好的方法,而不必在递归中更改源数组。

$array = array(
    1 => array(
        2 => 2,
        4 => 4
    ),
    2 => array(
        3 => 3
    ),
    3 => array(
        5 => 5
    ),
    9 => array(
        6 => 6
    )
);

//we need the copy to delete there nodes that have been re-atached. Otherwise, we end up changing the array itself within recursion, which is not good
$arrayCopy = $array;

function recursive(&$array, &$arrayCopy) {
    foreach($array as $key => &$value) {
        //if we found the leaf node
        if(!is_array($value)) {
            // and there is something in the array copy with this index
            if(array_key_exists($key, $arrayCopy)) {
                // re-attach it to the initial array. $value is passed by reference. BTW, not a good approach as I stated above, but it works on the sample data
                $value = $arrayCopy[$key];
                // remove that node from array copy in order to not double process it.
                unset($arrayCopy[$key]);
                // call it again for the leaf-node value
                recursive($value, $arrayCopy);
            }
            // here is recursion exit, if we don't find anything in the arracy copy for the fiven leaf node
        } else {
            //recursive call it for the node
            recursive($value, $arrayCopy);
        }
    }
}
// launch the recursion
recursive($array, $arrayCopy);

// now we need to remove the nodes that have been removed from the array copy, i.e. the ones being re-attached. We could not do this in the recursion
$result = array();
foreach(array_keys($arrayCopy) as $initial_key) {
    $result[$initial_key] = $array[$initial_key];
}

var_dump($result);

答案 1 :(得分:0)

现在我使用这个函数修复它,我确信有一种更优雅的方式,因为它只在父类也在数组中时才有效,但是它可以工作

table-cell