Php 修改JSON数组

Php 修改JSON数组,php,json,Php,Json,我想知道如何修改我的代码(如下)以获得 { "contacts": [ { "id": "c200", "name": "Ravi Tamada", "email": "ravi@gmail.com", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "pho

我想知道如何修改我的代码(如下)以获得

{
"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"
            }
    },
而不是

 [
     {
         "Email":"john@appleseed.com",
         "Password":"4321",
         "lijst":"eieren, kaas, melk, 2 uien, brood(volkoren)",
         "fname":"John",
         "lname":"Doe",
         "PhoneNumber":"6123456"
     }
 ]
这是生成上述内容的代码:

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);
    }
}

那么您想添加一个名为
联系人
的键吗

在编码之前,请执行以下操作:

if($number != ""){
    echo json_encode(array('contacts' => $resultArray[$number]));
}else {
    echo json_encode(array('contacts' =>$resultArray));
}

请发布您为达到这一点所做的PHP。它是一个JSON字符串。您不直接处理json字符串。处理一个原生php数组/对象,然后将其编码为json,生成一个php数组。您给该数组一个名为
'contacts'
的键。将其值设置为联系人对象数组。然后根据GolezTrol的请求,将array.phpCode设置为
json\u encode()