I have working code which write result into array but values are doubled. Here is code:
<?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);
but it produces JSON like this
[
{
"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"
}
]
Could someone tell me what is wrong with aboove PHP code so it does not produce double records in JSON. Thank you
mysqli->fetch_array() uses MYSQLI_BOTH as default result type. Use the right paramater for the result you want.
mixed mysqli_fetch_array ( mysqli_result $result [, int $resulttype = MYSQLI_BOTH ] )
Result Type:
This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH.
By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function. The final option MYSQLI_BOTH will create a single array with the attributes of both.
Change
$row = $result->fetch_array()
To
$row = $result->fetch_array(MYSQLI_ASSOC)
When fetching the result use the MYSQLI_ASSOC
option. Also, you can save looping through the data, by immediately indexing it by ID in the initial while
loop.
$sql = "SELECT firstname, lastname, ID, parentID FROM table";
$result = $conn->query($sql);
$index = [];
while(($row = $result->fetch_array(MYSQLI_ASSOC))) {
$index[$row['ID']] = $row;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.