>我有一个使用以下php代码生成的json数据
$index = array();
foreach($rows as $row)
{
$row['data'] []= (object) [];
$index[$row['cat_id']] = $row;
}
// build the tree
foreach($index as $id => &$row)
{
if ($id === 0) continue;
$parent = $row['parent'];
$index [$parent]['children'][] = &$row;
}
unset($row);
// obtain root node
$index = $index[0]['children'][0];
$json_data = json_encode($index, JSON_PRETTY_PRINT);
生成以下 JSON
{
"cat_id": "1",
"id": "RT",
"name": "root",
"parent": "0",
"url": "www.test.com",
"data": [
{}
],
"children": [
{
"cat_id": "4",
"id": "CI.001",
"name": "Test2",
"parent": "2",
"url": "www.test.com",
"data": [
{}
]
}
我想要的是输出是这样的
var something = [{
"cat_id": "1",
"id": "RT",
"name": "root",
"parent": "0",
"url": "www.test.com",
"data": [
{}
],
"children": [
{
"cat_id": "4",
"id": "CI.001",
"name": "Test2",
"parent": "2",
"url": "www.test.com",
"data": [
{}
]
}];
我在网上浏览了一些建议它不是 json,而是我对 json 不熟悉的 php 数组。我该如何解决这个问题?
这是我
目前的解决方案。
ob_start();
echo "var javascript_array = [". $json_data . "];n";
$content = ob_get_contents();
file_put_contents('../core/json/tree.js', $content);
任何建议和改进将不胜感激。