【发布时间】:2020-07-11 04:01:39
【问题描述】:
我正在尝试创建一个 javascript 对象作为引导树视图的输入。我有从 mysql 和 json 获取数据的 php 将结果编码为以下结构:
{"Company 1":{"Production":["Brands","Categories","Products","Stocks"],"Sales":["Customers","Orders","Staffs","Stores"]},"Company 2":{"Production":["Brands","Categories","Products","Stocks"],"Sales":["Customers","Orders","Staffs","Stores"]}}
生成该 json 的 PHP 代码:
$databases=[];
foreach($result as $row){
$database=$row["database"];
$schema=$row["schema"];
$table=$row["object"];
if(!array_key_exists($database, $databases))
$databases[$database]=[];
if(!array_key_exists($schema, $databases[$database]))
$databases[$database][$schema]=[];
array_push($databases[$database][$schema], $table);
}
echo json_encode($databases);
但我正在努力将该 json 结构放入所需的 JavaScript 对象的嵌套数组中。下面是所需的结构:
[ { text: "Company 1", nodes: [ { text: "Production", nodes: [ { text: "Brands" }, { text: "Categories" }, { text: "Products" }, { text: "Stocks" } ] }, { text: "Sales", nodes: [ { text: "Customers" }, { text: "Orders" }, { text: "Staffs" }, { text: "Stores" } ] } ] }, { text: "Company 2", nodes: [ { text: "Production", nodes: [ { text: "Brands" }, { text: "Categories" }, { text: "Products" }, { text: "Stocks" } ] }, { text: "Sales", nodes: [ { text: "Customers" }, { text: "Orders" }, { text: "Staffs" }, { text: "Stores" } ] } ] } ];
任何建议将不胜感激
【问题讨论】:
-
如果可以显示PHP数组$result,那么我们就很容易弄清楚数组的结构以及如何操作它了。
标签: javascript php json