【发布时间】:2014-01-19 03:19:21
【问题描述】:
新年快乐!假设 user1 位于邮政编码 12345。我想在距离该邮政编码 X 英里内找到其他用户。
首先,我创建了表单:
<div id="wrapper">
<form action="L1.php" method="post">
<select name="radius">
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
Miles within Zip Code:
<input name="zip" type="text" value="13126" />
<input type="submit" value="refine" />
</form>
</div>
现在我列出了距离 12345 X 英里以内的所有邮政编码:(L1.php):
<?php
include('includes/db_AF.php'); //includes the db credentials
$connection = @new mysqli(HOSTNAME, MYSQLUSER, MYSQLPASS, MYSQLDB);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//look up the zip code in the searchbox
$whereClauses = array();
if (! empty($_POST['zip'])) $whereClauses[] ="zip_code='".mysqli_real_escape_string($connection,$_POST['zip'])."'";
$where = '';
if (count($whereClauses) > 0) { $where = ' WHERE '.implode(' AND ',$whereClauses); }
$sql = "SELECT * FROM zip " .$where." ";
$result=mysqli_query($connection,$sql) or die("Error: ".mysqli_error()."<br />Query: ".$sql);
//find out the corresponding lat and long
while ($row = mysqli_fetch_assoc($result)) {
echo '<br />';
echo '<br />';
$lat=$row['latitude'];
echo '<br />';
$lon=$row['longitude'];
echo '<br />';
}
$radius=$_POST['radius'];
//here I am generating an array of all the zip codes within x miles from 12345.
$query="SELECT * FROM zip WHERE (3958*3.1415926*sqrt((latitude-'$lat')*(latitude-'$lat') + cos(latitude/57.29578)*cos('$lat'/57.29578)*(longitude-'$lon')*(longitude-'$lon'))/180) <= '$radius'";
$result_obj = '';
$result_obj = $connection->query($query);
while($resultx = $result_obj->fetch_array(MYSQLI_ASSOC)) {
$items[] = $resultx;
}
foreach ($items as $item) {
echo $item['zip_code'];
echo '<br />';
}
$queryz="SELECT zip FROM customer"; // I am generating an array of all customer zip codes.
$resultz_obj = '';
$resultz_obj = $connection->query($queryz);
while($resultzz = $resultz_obj->fetch_array(MYSQLI_ASSOC)) {
$itemsz[] = $resultz;
}
$resultv = array_intersect($items, $itemsz);
print_r($resultv);
所以现在我有一个邮政编码数组。我想列出住在这些邮政编码的用户。我知道我必须相交两个数组,但得到“注意:数组到字符串的转换”错误。有什么想法吗?
【问题讨论】:
-
我有点困惑。您在数组中有邮政编码,并且您想从该邮政编码中获取所有用户。对吗?
-
也许尝试将邮政编码数组转换为逗号分隔的字符串,然后执行
SELECT * FROM customer WHERE zip IN ( $comma_seperated_zip_codes ) -
是的,$items 是距离 12345 5 英里范围内的邮政编码数组。$itemsz 是所有客户的邮政编码数组。
标签: php mysql arrays search zip