我想知道是否有人可以通过编码问题指出我正确的方向。
我在PHP中运行while循环,将后置代码与另一个循环代码进行比较,并且循环的每次运行都会生成距离数据。我想做的就是对这些数据进行排序并显示它。
通常我会将所有内容都放入MySQL数据库然后按照这种方式进行排序,但我认为这会超过杀戮。
以下是循环的示例:
while($row = mysql_fetch_array($result))
{
$info = get_driving_information($_POST['customerpostcode'], $row[instructor_postcode]);
echo $row['instructor_name'] . " - " . $info['distance'];
}
我知道这可能是PHP 101,但我以前从未做过这样的事情,也不确定如何。
提前感谢您的阅读,
里克多维
答案 0 :(得分:1)
我认为这就是你的意思:
$rows = array();
while($row = mysql_fetch_array($result))
{
$info = get_driving_information($_POST['customerpostcode'], $row[instructor_postcode]);
$row['distance'] = $info['distance']; // store it in the array
$rows[] = $row;
}
然后使用usort
按距离键对$rows
数组进行排序。
答案 1 :(得分:1)
$data = array();
while($row = mysql_fetch_assoc($result)) {
$info = get_driving_information($_POST['customerpostcode'], $row['instructor_postcode']);
$data[$row['instructor_name']] = $info['distance'];
}
asort($data);
foreach ($data as $instructor => $distance) echo "$instructor - $distance<br />\n";
这将按教师姓名排序。如果需要按距离排序,只需反转数据存储在临时数组中的方式,即I.E. $data[$row['distance']] = $info['instructor_name'];
。
如果您用作临时数组键的值出现多次,则无法使用此操作,因为您必须使用array_multisort()。
$data = $instructors = $distances = array();
for ($i = 0; $row = mysql_fetch_assoc($result); $i++) {
$info = get_driving_information($_POST['customerpostcode'], $row['instructor_postcode']);
$instructors[$i] = $row['instructor_name'];
$distances[$i] = $row['distance'];
$data[$i] = array('instructor'=>$row['instructor_name'],'distance'=>$info['distance']);
}
array_multisort($instructors,SORT_DESC,$distances,SORT_ASC,$data);
foreach ($data as $entry) echo "{$entry['instructor']} - {$entry['distance']}<br />\n";
答案 2 :(得分:1)
我建议将每个距离结果存储在数组中,然后对数组应用排序。例如:
$distances = array();
while($row = mysql_fetch_array($result))
{
$info = get_driving_information($_POST['customerpostcode'], $row[instructor_postcode]);
$distances[$info['distance']] = $row['instructor_name'] . " - " . $info['distance'];
}
if(ksort($distances)) {
foreach($distances as $key=>$value) {
echo $value;
}
}
请注意,如果精确距离在阵列中出现多次,我的解决方案将不适用于您;如果这看起来很可能,那么您可能需要一个不同的基于阵列的解决方案。
有关数组排序的更多信息,请参阅PHP手册中的Sorting Arrays。
答案 3 :(得分:0)
即使您在阵列中有多次相同的instructor_name或距离,这也会有效。另外购买修改cmp()函数,您可以按任何其他标准对整个事物进行排序。
$drivers = array();//initialising an array
while($row = mysql_fetch_array($result))
{
$info = get_driving_information($_POST['customerpostcode'], $row[instructor_postcode]);
$drivers[]=row;//adding new item to array
}
$drivers = usort($drivers,'cmp'); // sorting array using custom comparison function "cmp()"
foreach ($drivers as $driver) //printing results
echo $driver['instructor_name'] . " - " . $driver['distance'];
//custom comparison function
function cmp($a, $b) //returns +1 if $a > $b, -1 if $a < $b, else returns 0
{
if ($a['distance']>$b['distance'])
return 1;
if ($a['distance']<$b['distance'])
return -1;
return 0;
//quicker solution is to "return $a['distance']-$b['distance'];"
}