Я могу построить хорошо сформированный JSON, который выглядит следующим образом:
{
"id": "1",
"parent_id": "0",
"name": "Electronics",
"children": [{
"id": "2",
"parent_id": "1",
"name": "Television",
"children": [{
"id": "3",
"parent_id": "2",
"name": "Smart"
}, {
"id": "4",
" parent_id": "2",
"name": "4K Ultra"
}, {
"id": "5",
"parent_id": "2",
" name": "Curved"
}]
}]
}
Но я действительно хочу JSON в этом формате:
[{
"type": "view",
"name": "db_view_1",
"depends": [
"db_table_15",
"db_table_14",
"db_table_1"
]
}, {
"type": "view",
"name": "db_view_2",
"depends": [
"db_table_4",
"db_table_14"
]
}, {
"type": "view",
"name": "db_view_3",
"depends": [
"db_table_5",
"db_table_14"
]
}]
Как вы можете см. в ключе «зависимость», значение является массивом строк, без ключа, только значение.
Я использовал этот код PHP для генерации первого JSON вывода:
// Get the tree array from DB
$treeArray = getDataFromDatabase();
// Group by parent id
$treeArrayGroups = [];
foreach ($treeArray as $record) {
$treeArrayGroups[$record['parent_id']][] = $record;
}
// Get the root
$rootArray = $treeArray[0];
// Transform the data
$outputTree = transformTree($treeArrayGroups, $rootArray);
// Output the response
header('Content-Type: application/json');
echo json_encode($outputTree);
/**
* Transform the tree
*
* @param $treeArrayGroups
* @param $rootArray
* @return mixed
*/
function transformTree($treeArrayGroups, $rootArray)
{
// Read through all nodes where parent is root array
foreach ($treeArrayGroups[$rootArray['id']] as $child) {
// If there is a group for that child, aka the child has children
if (isset($treeArrayGroups[$child['id']])) {
// Traverse into the child
$newChild = transformTree($treeArrayGroups, $child);
} else {
$newChild = $child;
}
// Assign the child to the array of children in the root node
$rootArray['children'][] = $newChild;
}
return $rootArray;
}
/**
* Get all records from DB and return array
*
* @return array
*/
function getDataFromDatabase()
{
$config = parse_ini_file('config/myconfig.ini');
if($config == false){
echo "Can't find config file";
}
// Create connection
$conn = new mysqli('localhost',$config['username'], $config['password'], $config['dbname']);
//$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$nodes="SELECT id, parent_id, name FROM nested";
$records = $conn->query($nodes);
$output = mysqli_fetch_all($records, MYSQLI_ASSOC);
mysqli_close($conn);
return $output;
}
Но я не знаю, как изменить мой код для получения второго JSON вывода.
Спасибо за вашу помощь!