Question

I would like to know how I can modify my code (below) to obtain

{
"contacts": [
    {
            "id": "c200",
            "name": "Ravi Tamada",
            "email": "ravi@gmail.com",
            "address": "xx-xx-xxxx,x - street, x - country",
            "gender" : "male",
            "phone": {
                "mobile": "+91 0000000000",
                "home": "00 000000",
                "office": "00 000000"
            }
    },

instead of

 [
     {
         "Email":"john@appleseed.com",
         "Password":"4321",
         "lijst":"eieren, kaas, melk, 2 uien, brood(volkoren)",
         "fname":"John",
         "lname":"Doe",
         "PhoneNumber":"6123456"
     }
 ]

This is the code generating the above:

if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM UserInfo";

// Check if there are results
if ($result = mysqli_query($con, $sql)) {
    // If so, then create a results array and a temporary one
    // to hold the data
    $resultArray = array();
    $tempArray = array();

    // Loop through each row in the result set
    while($row = $result->fetch_object()) {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    // number is if u add ?k to the URL u will only get that output!
    if ($number != "") {
        echo json_encode($resultArray[$number]);
    } else {
        echo json_encode($resultArray);
    }
}
Was it helpful?

Solution

So you want to add a key called contacts ?

right before encoding, do the following:

if($number != ""){
    echo json_encode(array('contacts' => $resultArray[$number]));
}else {
    echo json_encode(array('contacts' =>$resultArray));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top