PHP排序导致代码逻辑

时间:2012-01-19 16:12:00

标签: php codeigniter

好的我有一个结果集,我正在循环,外卖对象有以下属性id,名称,地址,邮政编码,距离,mile_cost,比萨饼,中国,印度,烤肉串。如果他们有披萨菜单,那么它将包含1或0,如果不是等等

我想过滤结果,以便获得最近的单一披萨,中国,印度和烤肉串卖餐馆。但也要过滤结果,使其不会显示距离大于10且大于单个外卖最大传送距离的结果。

我必须在PHP代码而不是mysql查询中执行此操作,我有点难过如何做到这一点。这就是我到目前为止所拥有的

 foreach($takeaway as $takeaway){

        $distance = $this->geozip->get_distance($location, $takeaway->postcode);//get the distance between the two postcodes 

        if($distance <= $takeaway->distance && $distance <= 10){

            $number = 0;

            echo $takeaway->name.' is '.$distance.'miles away <br />';

         ?>  
           <div class="takeaway_box">
               <div class="takeaway_box_band">Indian</div>

           </div>                
 <?php
        } 
    }
  ?>  

我想为了得到每种类型最近的单一餐厅,我必须找到距离最接近零的那家,然后点一下怎么样?

非常感谢任何有关如何做到这一点的帮助。

1 个答案:

答案 0 :(得分:0)

使用array_filter过滤结果。 然后使用usort按距离排序。

例如:

function filter_function($takeaway) {
  return $takeaway->someProperty == 1; // could be your menu;
}

function sort_function($a, $b) {
  // distance must be set before elements are passed trough the sort function
  $ad = $a->distance;
  $bd = $b->distance;

  // sort is ASC 
  if ($ad == $bd) {
      return 0;
  }
  // todo DESC change the < operator to >
  return ($ad < $bd) ? -1 : 1;  
}

$takeaways = array_filter($takeaways, filter_function);
usort($takeaways, sort_function);