我有以下示例數組列表;列表樹結構
$relationships = ['contact', 'property', 'contact.type1', 'contact.type2', 'contact.type1.color1', 'contact.type1.color2'];
我想要一個這樣的結構;
[
contact => [
type1 => [
color1 => [],
color2 => []
],
type2 => []
],
property => []
]
我創建了下面的代碼;
start();
function start()
{
$myTree = array();
$relations = ['contact', 'property', 'contact.type1', 'contact.type2', 'contact.type1.color1', 'contact.type1.color2'];
foreach ($relations as $relation) {
$myTree = getRelationTree($relation, $myTree);
}
var_dump($myTree);
}
function getRelationTree($name, $tree)
{
$sections = explode('.', $name);
$main = array_shift($sections);
if (!array_search($main, $tree)) {
$tree[$main] = [] ;
}
// Has nested relationships
if (count($sections) > 0) {
$children = [];
$children[] = getRelationTree(join('.',$sections), $children);
$tree[$main] = $children;
}
return $tree;
}
不過,我得到的結果是缺少color1
按照上述預期的結果。
你能告訴我我的代碼出了什麼問題,以及如何修復它以給我想要的結果?謝謝
我真的被它的邏輯要變換數組到所需的格式排列不明白?請告訴我? –
這是一個業務需求。我在這裏給出的例子只是我將要接受的結構樣本和我需要輸出的結構。 –
如果沒有邏輯背後,那麼爲什麼你不手動hardcord該類型的數組 –