Dio*_*lor 0 php mysql json compare 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."')";
Run Code Online (Sandbox Code Playgroud)
既然我们已经缩小了结果,我们希望匹配'id'第一个表的行(如果存在于第二个表中).成功的我们创造了结果.
所以让我们先得到一些数字:
$result1 = mysql_query($sql1);
$result2 = mysql_query($sql2);
$numRows1 = mysql_num_rows($result1);
$numRows2 = mysql_num_rows($result2);
$loopCount1 = 1;
$loopCount2 = 1;
Run Code Online (Sandbox Code Playgroud)
为了更有效地解析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 .= ']}';
Run Code Online (Sandbox Code Playgroud)
最后一个回声:
echo $json;
Run Code Online (Sandbox Code Playgroud)
要将两个表的值和打印结果作为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);
?>
Run Code Online (Sandbox Code Playgroud)