将`mysqli_fetch_array`作为一个带有json对象的字符串发送

时间:2016-06-15 20:54:46

标签: php json

我有以下代码,用于生成数组并将其发送回主页并将其附加到现有表中。

我只是想知道是否有任何可能的方法将以下代码生成的数据作为JSON对象中的单个元素发送。

例如:

{"arraydata":"Data Generated From The below Code","another variable":"some other data"}

等等...

任何建议??

     $result = mysqli_query($con," SELECT * FROM `BIMTECH_academy_2016_classes` 
               WHERE  `Serial`='$serial' ORDER BY `Serial` ");

     while($row = mysqli_fetch_array($result))
     {
           echo "<tr id='" . $row['Serial'] . "'>";
               echo "<td><img src='images/delete-icon.svg' id='classDeleteIcon'/></td>";
               echo "<td class='datepicker' id='Date'>" . $row['Date'] . "</td>";
               echo "<td class='timepicker' id='From'>" . $row['From'] . "</td>";
               echo "<td class='timepicker' id='To'>" . $row['To'] . "</td>";
           echo "</tr>";
     }

1 个答案:

答案 0 :(得分:0)

在while循环之前声明一个变量($ html)。将所有数据(html和$ rows值)追加/连接到$ html变量。创建一个具有不同键和值的数组,一个键包含$ html变量作为值。

$html = ''; // a variable
while($row = mysqli_fetch_array($result))
{  // concat all data to $html
   $html.="<tr id='" . $row['Serial'] . "'>";
   $html.="<td><img src='images/delete-icon.svg' id='classDeleteIcon'/></td>";
   $html.="<td class='datepicker' id='Date'>" . $row['Date'] . "</td>";
   $html.="<td class='timepicker' id='From'>" . $row['From'] . "</td>";
   $html.="<td class='timepicker' id='To'>" . $row['To'] . "</td>";
   $html.="</tr>";
}
$data_array = array(); // declare array
$data_array['arraydata'] = $html; // assign to array key
$data_array['otherdata'] = 'otherdata'; // other data to the array
$json_data = json_encode($data_array, JSON_HEX_QUOT | JSON_HEX_TAG); // encode array with html tags
echo $json_data;

输出:

{"arraydata":" your html data","otherdata":"otherdata"}