简体   繁体   中英

Sort foreach loop result

I want to sort it by $distance base in foreach loop in my VIEWS.. so heres my code in Models

    $db = $this->getDbo();
    $query = $db->getQuery(true)
                ->select('*')
                ->from('#__load');

    $db->setQuery($query);               
    $db->query();
    $rows = $db->loadObjectList();
    return $db->loadObjectList();

This is the code in my View where i want to sort it by distance

  foreach ($this->items as $i => $item) {  
       $distance = $item->result1 * $item->result2        
  sort($distance)
}

echo $distance

result

3, 6, 2, 7, 8

i want to show like this

2, 3, 6, 7, 8

sort works on an array, and what you are doing is you are calling sort on every item in the array which wont work.

What you can do instead is do your foreach loop and then sort after:

  $array = [];
  foreach ($this->items as $i => $item) {  
      $distance = $item->result1 * $item->result2;        
      $array[] = $distance;
  }
  sort($array);
  var_dump($array);

https://www.php.net/manual/en/function.sort.php

First Convert your result $this->items into (array)$this->items and then use one of the following function:

sort() - sort arrays in ascending order
rsort() - sort arrays in descending order
asort() - sort associative arrays in ascending order, according to the value
ksort() - sort associative arrays in ascending order, according to the key
arsort() - sort associative arrays in descending order, according to the value
krsort() - sort associative arrays in descending order, according to the key

and get sorted value.

There are a few things here that don't make sense to me, so I'll blindly try to refactor your scripts and put all of the processing in the model where it belongs (you shouldn't be manipulating data in the view).

Untested snippet:

$db = $this->getDbo();
$query = $db->getQuery(true)
            ->select('result1 * result2')
            ->from('#__load')
            ->orderBy(1);
$db->setQuery($query);               
return $db->loadColumn();

Relevant pages to read:

I expect that your view will now receive the following sorted and indexed array:

$this->items = [2, 3, 6, 7, 8];

If you are a Joomla user, come join us at Joomla Stack Exchange . Have a browse of my answers to mysql tagged questions for explained examples and best practices.

If you are living in Brisvegas, come to our monthly Joomla User Group Meetup in West End (we aren't scary people). This is a place where you can leverage an IRL network of people that want to help you grow your skills and get your projects finished.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM