使用mysql_fetch_array时,我将数组数据传递给单独的变量。我的问题是如何按位置访问该阵列中的不同项目? 我希望依次调用每个项目对该项目进行计算运行,如果结果是目前为止的最低数字,则将该数据传递给变量。
感谢任何帮助,谢谢。
<?php
$query = "SELECT postcode FROM freelance ORDER BY id";
$result = mysql_query($query);
while($postcode = mysql_fetch_array($result)) {
echo "<span>" . $postcode['postcode'] . "</span></br>";
}
?>
不是回显出所有邮政编码,而是如何定义只输出数组中的第三项
答案 0 :(得分:0)
解决方案1:
您可以在while中使用foreach
显示它们:
foreach($postcode as $data) {
echo $data;
}
解决方案2:
您可以按位置调用它们(从0开始):
$postcode[0]
$postcode[1]
$postcode[2]
...
阅读有关数组的更多信息:http://www.php.net/manual/de/language.types.array.php
答案 1 :(得分:0)
当您致电mysql_fetch_array
时,您将获得查询返回的下一行的结果。在这种情况下,您的查询返回的结果集包含一列postcode
和多行(可能)。您的while
循环只是获取每一行的postcode
值,并在<span>
中回显它。
编辑:我已将我的代码示例更改为OP的评论。
我对你想要做的事情并不熟悉,但希望我的例子有道理(你必须用你的代码填写一些空白)。首先,我认为您不需要将数据库中的结果存储到一个大数组中,然后遍历每个记录以确定最低距离。您已经在while循环中循环遍历每条记录,请使用它!
<?php
$inputcoords = //I assume that you already have the coordinates for the input postal code somewhere
$query = "SELECT postcode FROM freelance ORDER BY id";
$result = mysql_query($query);
while($postcode = mysql_fetch_array($result)) {
$curpostcode = $postcode['postcode'];
$curcoords = //calculation/function/something that calculates the current coordinates from $curpostcode
$distance = //Haversine formula using $curcoords and $inputcoords (you'll have to figure this part out)
if (!isset($lowest) || $distance < $lowest) {
$lowest = $distance;
//optional: if you want to keep track of which postal code gave the shortest distance...
$lowestpostcode = $curpostcode;
}
}
//go on to use the calculated distances for something...
?>