1

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

1

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Change

$row = $result->fetch_array()

To

$row = $result->fetch_array(MYSQLI_ASSOC)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.