1
請看下面的例子:轉換表狀陣列的樹狀排列
function tableToTree($array, $parents)
{
$result = [];
$p = $parents;
foreach ($array as $k => $row) {
$result[$row[$p[0]]][$row[$p[1]]]= $row[$p[2]]; // **
}
return $result;
}
$foo = [
['x' => 'a', 'y' => 'n','z'=>'AA'],
['x' => 'a', 'y' => 'm','z'=>'BB'],
['x' => 'b', 'y' => 'v','z'=>'CC'],
['x' => 'b', 'y' => 'w','z'=>'DD'],
];
print_r(tableToTree($foo, ['x', 'y','z']));
其中產量:
Array
(
[a] => Array
(
[n] => AA
[m] => BB
)
[b] => Array
(
[v] => CC
[w] => DD
)
)
上面的代碼只有當只有兩個家長工作。如何改寫**
表示的行,以便與任意數量的父母一起工作。
你什麼名字作爲 '父母'?添加'['x'=>'c','y'=>'w','z'=>'DD']'至$ foo – splash58