我有工作代碼寫入數組結果,但價值倍增。這裏是代碼:PHP MySql選擇陣列
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "databasename";
// 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 firstname, lastname, ID, parentID FROM table";
$result = $conn->query($sql);
while($row = $result->fetch_array()){
$rows[] = $row;
}
// create an index on id
foreach($rows as $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);
// obtain root node
$index = $index[0]['children'];
/* free result set */
$result->close();
/* close connection */
$conn->close();
// output json
echo json_encode($index, JSON_PRETTY_PRINT);
,但它產生的JSON這樣
[
{
"0": "Luka",
"firstname": "Luka",
"1": "Some",
"lastname": "Some",
"2": "287",
"ID": "287",
"3": "277",
"parentID": "277"
},
{
"0": "John",
"firstname": "John",
"1": "Test",
"lastname": "Test",
"2": "4080",
"ID": "4080",
"3": "277",
"parentID": "277"
}
]
有人能告訴我什麼是錯的aboove PHP代碼,因此它不會在JSON產生雙重記錄。 謝謝
的可能的複製[在我的數組雙結果(MySQL的\ _fetch \ _array)](http://stackoverflow.com/questions/9556794/double-results-in-my-array-mysql-fetch- array) – TopCheese