目前我将json放在下面
[
{
"ID": 1479,
"Name": "praven",
"Number": "007",
"Image": ""
}
]
目前用于生成此代码的PHP代码如下所示
<?php
require_once(dirname(__FILE__).'/connectionInfoTest.php');
//Set up our connection
$connectionInfo = new ConnectionInfo();
$connectionInfo->GetConnection();
if (!$connectionInfo->conn)
{
//Connection failed
echo 'No Connection';
}
else
{
//Create query to retrieve all contacts
$query = 'SELECT * FROM Contacts ORDER BY Contacts_ID';
$stmt = sqlsrv_query($connectionInfo->conn, $query);
if (!$stmt)
{
//Query failed
echo 'Query failed';
}
else
{
$contacts = array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$contact= array("ID" => $row['Contacts_ID'],
"Name" => $row['Contacts_Name'],
"Number" => $row['Contacts_Number'],
"Image" => base64_encode($row['Contacts_Image'])
);
//Add the contact to the contacts array
array_push($contacts, $contact);
}
//Echo out the contacts array in JSON format
header('Content-type: application/json');
echo json_encode($contacts,JSON_PRETTY_PRINT);
}
}
?>
但问题是我期待的输出如下
{
"contacts": [{
"ID": 1452,
"Name": "John",
"Number": "1452",
"Image": ""
}]
}
那么我应该在PHP中找到什么才能获得我期待的预期呢?谢谢。
答案 0 :(得分:3)
使用此代码:
在此处替换您的代码:
//Echo out the contacts array in JSON format
header('Content-type: application/json');
$output = ['contacts' => $contacts];
echo json_encode($output, JSON_PRETTY_PRINT);
答案 1 :(得分:0)
使用此代码
$contacts = array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$contacts[] = array("ID" => $row['Contacts_ID'],
"Name" => $row['Contacts_Name'],
"Number" => $row['Contacts_Number'],
"Image" => base64_encode($row['Contacts_Image'])
);
}
//Echo out the contacts array in JSON format
header('Content-type: application/json');
echo json_encode(['contacts' => $contacts],JSON_PRETTY_PRINT);