Я создаю записи MySQL в массиве JSON, но, кажется, есть некоторые проблемы с набором данных JSON. Код PFB: —
Выходит JSON:
[{
"ID": "1",
"Coupon_ID": "ABC1",
"Campaign_ID": "353",
"Campaign_Name": "Test1",
"Title": "Test1",
"Description": "Test1",
"Category": "Test1",
"Type": "Coupon",
"Type_Value": "1231",
"Tracking_URL": "http://abc1.com",
"Added_Date": "2016-07-13",
"Expiry_Date": "2016-07-28"}][
{
"ID": "2",
"Coupon_ID": "ABC2",
"Campaign_ID": "3532",
"Campaign_Name": "Test2",
"Title": "Test2",
"Description": "Test2",
"Category": "Test2",
"Type": "Coupon",
"Type_Value": "1232",
"Tracking_URL": "http://abc2.com",
"Added_Date": "2016-07-13",
"Expiry_Date": "2016-07-28"}]
Я хочу что-то вроде этого: —
[{
"ID": "1",
"Coupon_ID": "ABC1",
"Campaign_ID": "353",
"Campaign_Name": "Test1",
"Title": "Test1",
"Description": "Test1",
"Category": "Test1",
"Type": "Coupon",
"Type_Value": "1231",
"Tracking_URL": "http://abc1.com",
"Added_Date": "2016-07-13",
"Expiry_Date": "2016-07-28"}
{
"ID": "2",
"Coupon_ID": "ABC2",
"Campaign_ID": "3532",
"Campaign_Name": "Test2",
"Title": "Test2",
"Description": "Test2",
"Category": "Test2",
"Type": "Coupon",
"Type_Value": "1232",
"Tracking_URL": "http://abc2.com",
"Added_Date": "2016-07-13",
"Expiry_Date": "2016-07-28"}]
Я имею в виду [] эти скобки вместо того, чтобы приходить для каждой записи, они должны встречаться только один раз.
Код PHP: —
<?php
header('Content-type: application/json');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "couponsdeals";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$apikey = $_GET['API_KEY'];
$sql = "SELECT AFF_ID FROM api WHERE API_KEY= '$apikey' ";
//$sql1= "SELECT ID,Coupon_ID,Campaign_ID,Campaign_Name,Title,Description,Category,Type,Type_Value,Tracking_URL,Added_Date,Expiry_Date FROM couponcode_table ";
$sql1 = "SELECT * FROM couponcode_table ";
$result = $conn->query($sql);
$result1 = $conn->query($sql1);
if ($result) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$data = $row["AFF_ID"];
if ($result1) {
while ($row1 = $result1->fetch_assoc()) {
$data1 = $row1["Tracking_URL"];
$mydata = explode("&", $data1);
if (isset($mydata[2])) {
$json1 = array();
$mydata2 = $mydata[0] . "&aff_id=" . $data . "&" . $mydata[2];
$values = array(
'ID' => $row1['ID'],
'Coupon_ID' => $row1['Coupon_ID'],
'Campaign_ID' => $row1['Campaign_ID'],
'Campaign_Name' => $row1['Campaign_Name'],
'Title' => $row1['Title'],
'Description' => $row1['Description'],
'Category' => $row1['Category'],
'Type' => $row1['Type'],
'Type_Value' => $row1['Type_Value'],
'Tracking_URL' => $mydata2,
'Added_Date' => $row1['Added_Date'],
'Expiry_Date' => $row1['Expiry_Date']
);
array_push($json1, $values);
echo json_encode($json1, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
} else {
$json = array();
$mydata1 = $mydata[0] . "&aff_id=" . $data;
$value = array(
'ID' => $row1['ID'],
'Coupon_ID' => $row1['Coupon_ID'],
'Campaign_ID' => $row1['Campaign_ID'],
'Campaign_Name' => $row1['Campaign_Name'],
'Title' => $row1['Title'],
'Description' => $row1['Description'],
'Category' => $row1['Category'],
'Type' => $row1['Type'],
'Type_Value' => $row1['Type_Value'],
'Tracking_URL' => $mydata1,
'Added_Date' => $row1['Added_Date'],
'Expiry_Date' => $row1['Expiry_Date']
);
array_push($json, $value);
echo json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
}
}
}
} elseif (!$result) {
echo "0 results";
}
$conn->close();
?>
Вам нужно инициализировать / отобразить ваш массив JSON вне циклов while:
$json = array();
while(....) {
while(....) {
//.......
array_push($json, $value);
//.......
}
}
echo json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
Я просто изменяю ваш код, пробую этот код, надеюсь, вы получите ожидаемый результат.
<?php
header('Content-type: application/json');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "couponsdeals";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$apikey = $_GET['API_KEY'];
$sql = "SELECT AFF_ID FROM api WHERE API_KEY= '$apikey' ";
//$sql1= "SELECT ID,Coupon_ID,Campaign_ID,Campaign_Name,Title,Description,Category,Type,Type_Value,Tracking_URL,Added_Date,Expiry_Date FROM couponcode_table ";
$sql1= "SELECT * FROM couponcode_table ";
$result = $conn->query($sql);
$result1 = $conn->query($sql1);
if ($result) {
// output data of each row
$json = array();while($row = $result->fetch_assoc()) {
$data= $row["AFF_ID"];
if($result1){
while($row1 = $result1->fetch_assoc()) {$data1=$row1["Tracking_URL"];$mydata = explode("&",$data1);if(isset($mydata[2])){
$mydata2= $mydata[0]."&aff_id=".$data."&".$mydata[2];
$values =array(
'ID' => $row1['ID'],
'Coupon_ID' => $row1['Coupon_ID'],
'Campaign_ID' => $row1['Campaign_ID'],
'Campaign_Name' => $row1['Campaign_Name'],
'Title' => $row1['Title'],
'Description' => $row1['Description'],
'Category' => $row1['Category'],
'Type' => $row1['Type'],
'Type_Value' => $row1['Type_Value'],
'Tracking_URL' =>$mydata2,
'Added_Date' => $row1['Added_Date'],
'Expiry_Date' => $row1['Expiry_Date']
);array_push($json, $values);
} else {
$mydata1= $mydata[0]."&aff_id=".$data;
$value =array(
'ID' => $row1['ID'],
'Coupon_ID' => $row1['Coupon_ID'],
'Campaign_ID' => $row1['Campaign_ID'],
'Campaign_Name' => $row1['Campaign_Name'],
'Title' => $row1['Title'],
'Description' => $row1['Description'],
'Category' => $row1['Category'],
'Type' => $row1['Type'],
'Type_Value' => $row1['Type_Value'],
'Tracking_URL' =>$mydata1,
'Added_Date' => $row1['Added_Date'],
'Expiry_Date' => $row1['Expiry_Date']
);
array_push($json, $value);
}
}
}
}
echo json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
elseif(!$result) {
echo "0 results";
}
$conn->close();
?>
Если вы намереваетесь получить все данные, сгенерированные в цикле, вам может понадобиться просто сохранить все данные в переменной и отличить выходные данные
echo $whatever;
до конца вашего сценария и за пределами цикла. Таким образом, вы обязательно соберете все свои данные за один раз … Слегка измененные и прокомментированные ваш код ниже иллюстрирует все это лучше
<?php
header('Content-type: application/json');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "couponsdeals";
// CREATE A VARIABLE THAT WOULD HOLD ALL THE DATA (ARRAY GENERATED IN THE LOOP)
// INITIALIZE IT TO THE DEFAULT "FAILURE" MESSAGE..."0 Results"// THAT WAY; YOU WOULDN'T NEED ANY else if() CLAUSE...
$jsonData = array("message"=> "0 results");
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$apikey = $_GET['API_KEY'];
$sql = "SELECT AFF_ID FROM api WHERE API_KEY= '$apikey' ";
$sql1 = "SELECT * FROM couponcode_table ";
$result = $conn->query($sql);
$result1 = $conn->query($sql1);
$json = array();
$json1 = array();
if ($result) {
// output data of each row
while($row = $result->fetch_assoc()) {
$data = $row["AFF_ID"];
if($result1){
while($row1 = $result1->fetch_assoc()) {
$data1 = $row1["Tracking_URL"];
$mydata = explode("&",$data1);
if(isset($mydata[2])){
$json1 = array();
$mydata2 = $mydata[0]."&aff_id=".$data."&".$mydata[2];
$values = array(
'ID' => $row1['ID'],
'Coupon_ID' => $row1['Coupon_ID'],
'Campaign_ID' => $row1['Campaign_ID'],
'Campaign_Name' => $row1['Campaign_Name'],
'Title' => $row1['Title'],
'Description' => $row1['Description'],
'Category' => $row1['Category'],
'Type' => $row1['Type'],
'Type_Value' => $row1['Type_Value'],
'Tracking_URL' => $mydata2,
'Added_Date' => $row1['Added_Date'],
'Expiry_Date' => $row1['Expiry_Date']
);
// PUSH DATA TO THE $json1 VARIABLE
// AND DO NOT OUTPUT IT HERE YET... DIFFER IT
// TO THE END OF THE SCRIPT.
array_push($json1, $values);
}else{
$json = array();
$mydata1 = $mydata[0]."&aff_id=".$data;
$value = array(
'ID' => $row1['ID'],
'Coupon_ID' => $row1['Coupon_ID'],
'Campaign_ID' => $row1['Campaign_ID'],
'Campaign_Name' => $row1['Campaign_Name'],
'Title' => $row1['Title'],
'Description' => $row1['Description'],
'Category' => $row1['Category'],
'Type' => $row1['Type'],
'Type_Value' => $row1['Type_Value'],
'Tracking_URL' => $mydata1,
'Added_Date' => $row1['Added_Date'],
'Expiry_Date' => $row1['Expiry_Date']
);
// PUSH DATA TO THE $json VARIABLE
// AND DO NOT OUTPUT IT HERE YET... DIFFER IT
// TO THE END OF THE SCRIPT...
array_push($json, $value);
}
}
}
}
// NOW; OVERRIDE THE $jsonData VARIABLE WE CREATED ABOVE
// AND CREATE 2 ELEMENTS WITHIN IT 'json1' & 'json2'
// TO HOLD THE VALUES GENERATED WITHIN THE IF & ELSE CLAUSE RESPECTIVELY:SET ITS VALUE TO THE $json
$json = (!empty($json)) ? $json : array("message"=>"Empty Data-set for json");
$json1 = (!empty($json1)) ? $json1 : array("message"=>"Empty Data-set for json1");
// ASSIGN DATA FROM $json & $json1 TO THE $jsonData ARRAY...
$jsonData = array(
"json" => $json,
"json1" => $json1,
);
}
// NO NEED FOR ELSE CLAUSE BECAUSE IF THE "IF CLAUSE" DOES NOT RUN;
// WE HAVE A DEFAULT FOR THE $jsonData WHICH HAS A MESSAGE KEY
// CONTAINING THE DEFAULT MESSAGE WITHIN AN ARRAY...
// CLOSE DB CONNECTION
$conn->close();
// ECHO OUT THE JSON-ENCODED DATA AND EXIT THE SCRIPT USING DIE...
die( json_encode($jsonData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) );