2012-10-30 24 views
0

我有两个不同的表。对于那些我选择一些结果。 第一个基于最小/最大值,第二个基于Lat/Lng。这很简单(不支付对价值的关注),并创建:比较两个表的值和结果导出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阵列的位置作为对事件进行排序“持有人。这意味着,每个地点可能有几个事件。

某些地点可能没有事件,但也有一些事件可能不对应于地点。我们唯一的比较方法是相同的'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; 
+1

有没有你不使用的理由一个JOIN而不是在两个查询之间进行自己的匹配?你为什么手工创建JSON而不是使用'json_encode()'? – Barmar

+0

你内在的while循环只能在外循环的第一次迭代中工作,因为它获取'$ sql1'的所有结果,并且下次没有任何结果可以获取。您需要在内部循环之前执行'mysql_data_seek($ result1,0);'将其重置回到开始处。 – Barmar

回答

5

要比较两个表中的值,并打印结果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); 
?>