2 回答

TA貢獻(xiàn)1877條經(jīng)驗 獲得超1個贊
我建議使用遞歸flatItem函數(shù)來做到這一點。我還介紹了一個array_map_with_keys輔助函數(shù),因為 PHP 自己的array_map函數(shù)會忽略鍵,而在您的情況下,我們需要它。
function array_map_with_keys($callback, $array){
return array_map($callback, array_keys($array), $array);
}
function flatItem($key, $value) {
if(is_array($value)){
return
["text" => $key,
"nodes" => array_map_with_keys("flatItem", $value)
];
}else{
return ["text" => $value];
}
}
$converted = array_map_with_keys("flatItem", $databases);
echo json_encode($converted);
結(jié)果就是你所期望的:
[{"text":"Company 1","nodes":[{"text":"Production","nodes":[{"te
xt":"Brands"},{"text":"Categories"},{"text":"Products"},{"text":
"Stocks"}]},{"text":"Sales","nodes":[{"text":"Customers"},{"text
":"Orders"},{"text":"Staffs"},{"text":"Stores"}]}]},{"text":"Com
pany 2","nodes":[{"text":"Production","nodes":[{"text":"Brands"}
,{"text":"Categories"},{"text":"Products"},{"text":"Stocks"}]},{
"text":"Sales","nodes":[{"text":"Customers"},{"text":"Orders"},{
"text":"Staffs"},{"text":"Stores"}]}]}]
你可以把它傳遞給js。

TA貢獻(xiàn)1752條經(jīng)驗 獲得超4個贊
const data = {
"Company 1": {
"Production": ["Brands", "Categories", "Products", "Stocks"],
"Sales": ["Customers", "Orders", "Staffs", "Stores"]
},
"Company 2": {
"Production": ["Brands", "Categories", "Products", "Stocks"],
"Sales": ["Customers", "Orders", "Staffs", "Stores"]
}
}
function converter(data) {
return Object.entries(data).reduce((converted, [key, val]) => {
const element = {
text: key,
nodes: [...Object.entries(val).map(([key2, val2]) => {
return {
text: key2,
nodes: [...Object.values(val2).map(val3 => {
return {
text: val3
}
})]
}
})]
}
converted.push(element);
return converted
}, []);
}
console.log(converter(data))
- 2 回答
- 0 關(guān)注
- 168 瀏覽
添加回答
舉報