[英]Compare values of two tables and for results export JSON
我有兩個不同的表 。 對於那些我選擇一些結果 。 第一個基於最小/最大值,第二個基於緯度/經度。 這很容易(不必在值上多加注意),它是通過以下方式創建的:
$sql1="SELECT * FROM events WHERE value BETWEEN '".$min2d."' AND '".$max2d."'";
$sql2="SELECT * FROM locations WHERE (lng BETWEEN ".$wl." AND ".$el.") AND (lat BETWEEN '".$sl."'AND'".$nl."')";
現在我們縮小了結果的大小,如果第二個表上存在 'id'
行,那么我們要使其匹配 。 成功,我們創造結果。
因此,讓我們先獲取一些數字:
$result1 = mysql_query($sql1);
$result2 = mysql_query($sql2);
$numRows1 = mysql_num_rows($result1);
$numRows2 = mysql_num_rows($result2);
$loopCount1 = 1;
$loopCount2 = 1;
為了更有效地解析JSON (來自用戶),我們希望通過將事件創建到JSON數組(位置為“ holder”)中來對事件進行排序。 因此,每個位置可能有多個事件。
某些位置可能沒有事件 ,但是某些事件可能與位置不對應 。 我們唯一的比較方法是使用相同的'id'
。
通過下面的嘗試,即使對於沒有事件的位置,當然也會為所有 (錯誤的)位置結果產生錯誤。 這就是我需要您寶貴幫助的地方。
$json = '{"markers":[';
while ($row2 = mysql_fetch_array($result2)){
$json .= '{"coordinates": { "lat":'. $row2['lat'] .', "lng" : ' . $row2['lng'] .'},'
.'{"events" : [';
while ($row1 = mysql_fetch_array($result1)){
if ($row1['id']=$row2['id'])
$json .= '{ '
.'"title": "'.$row1['title'].'",'
.'"info": "'.$row1['info'].'",'
.'"}';
// add comma for Json if not final row
if ($loopCount1 < $numRows1) {
$json .= ', ';
$loopCount1++;}
}
$json .= ']}}';
// add comma for Json if not final row
if ($loopCount2 < $numRows2) {
$json .= ', ';
$loopCount2++;}
}
$json .= ']}';
最后是回聲:
echo $json;
要比較兩個表的值並將結果打印為json,請使用以下代碼,
<?php
/* connect to the db */
$link = mysql_connect('localhost','username','password') or die('Cannot connect to the DB');
mysql_select_db('db_name',$link) or die('Cannot select the DB');
/* grab the posts from the db */
$query1 = "SELECT * FROM test1";
$result1 = mysql_query($query1,$link) or die('Error query: '.$query1);
$query2 = "SELECT * FROM test2";
$result2 = mysql_query($query2,$link) or die('Error query: '.$query2);
/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result1) && mysql_num_rows($result2)) {
while($post1 = mysql_fetch_assoc($result1)) {
$post2 = mysql_fetch_assoc($result2);
if($post1['name'] == $post2['name'])
$posts[] = array('test1'=>$post1,'test2'=>$post2);
}
}
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
/* disconnect from the db */
@mysql_close($link);
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.