2 回答
TA贡献1877条经验 获得超1个赞
我建议使用递归flatItem函数来做到这一点。我还介绍了一个array_map_with_keys辅助函数,因为 PHP 自己的array_map函数会忽略键,而在您的情况下,我们需要它。
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);
结果就是你所期望的:
[{"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贡献1752条经验 获得超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 关注
- 129 浏览
添加回答
举报