比较两个表的值和结果导出JSON

时间:2012-10-30 04:57:05

标签: php mysql compare json nested-loops

我有两个不同的表。对于那些我选择一些结果的人。 在第一个基于最小值/最大值,第二个基于Lat / Lng。这很容易(不要过多关注值)并且由以下内容创建:

$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 个答案:

答案 0 :(得分: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);
?>