0

I have an Associative Array called $sqldata. This array looks like:

{"assignment":"1","grade":"11.00000"}

My Code:

function displayfetchAssignGrades($sqldata) {

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "moodle";
$sqlr = array();

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

foreach ($sqldata as $x => $sqld) {
$sqlqueryinfo = $sqld;
$sql = "SELECT name FROM mdl_assign WHERE id='$sqlqueryinfo'";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_array($result)) {
    $row["grade"] = $sqldata["grade"][$x];
    $sqlr = $row;
}
} else {
   echo "";
}

}
echo json_encode($sqlr);    
mysqli_close($conn);


}

What I want is as the foreach loop iterates I want the name of the assignment received from the SQL Query and the grade (from the original $sqldata array) in another associative. The order of the grades values corresponds to the Assignment Name. So the final array should look like in JSON:

{"assignment name":"Task 1","grade":"11.00000"}

1 Answers1

0

Try this:

$newArr = [];

if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_array($result)) {

        $newArr[] = array(
            'assignment name' => 'Task ' . $row["assignment"],
            'grade' => $row["grade"]
        );
    }
}

$json = json_encode($newArr, true);
Nitin
  • 898
  • 1
  • 9
  • 25