【发布时间】:2017-03-03 15:24:56
【问题描述】:
我有将记录导出为 JSON 的工作代码(请参见下文),现在我需要将记录导出为 CSV。 下面的代码具有“根节点”,这意味着它将导出 PARENTID=2 的成员及其所有子节点(递归)。 我需要的是导出的是给定 PARENTID 的记录,但以 CSV 格式而不是 JSON 格式。
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydataabse";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$index = array();
$sql = "SELECT NAME, ID, PARENTID FROM mytable";
$result = $conn->query($sql);
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$rows[] = $row;
$index[$row['ID']] = $row;
}
// build the tree
foreach($index as $id => &$row){
if ($id === 0) continue;
$parent = $row['PARENTID'];
$index[$parent]['children'][] = &$row;
}
unset($row);
// root node - exported are members with this PARENTID and all they children's
$index = $index[2]['children'];
/* free result set */
$result->close();
/* close connection */
$conn->close();
// output json
header('Content-Type: application/json');
echo json_encode($index, JSON_PRETTY_PRINT);
如果需要,这里是 mytable 结构:
ID PARENT NAME
1 0 John Doe
2 1 Sally Smith
3 2 Mike Jones
4 3 Jason Williams
5 4 Sara Johnson
6 1 Dave Wilson
7 2 Amy Martin
非常感谢。
【问题讨论】:
标签: php mysqli export-to-csv