Search code examples
arrayssortingmodx

MODx mysql array sort


I need to make a sorted list of filtered entries for MODx page. I have a several entries in db with 'table1' and columns 'id', 'name', 'someparam1' etc. I can print the whole list on the page with

$companies = $modx->getCollection('Company'); 
foreach($companies as $company) {
    $fields = $company->toArray();
    $output .= $modx->getChunk('showEntryTpl', $fields);
}
return $output;

but i still can't print the same list using recommendation#1 or recommendation#2: Example from MODx docs:

$c = $xpdo->newQuery('Box');
$c->innerJoin('BoxOwner','Owner'); // arguments are: className, alias
$c->where(array(
   'width' => 5,
   'Owner.user' => 2,
));
$c->sortby('name','ASC');
$c->limit(5);
$boxes = $xpdo->getCollection('Box',$c);

Using it this way

$sortingcriteria = 'id';

$s = $modx->newQuery('modResource');
$s->sortby($sortingcriteria,'ASC');
$out = $modx->getCollection('Company',$s);

return $out;

doesn't work. How can I sort the list by chosen column and then filter it?


Solution

  • Thank you Vasis and Sean Kimball for suggestions! This code pulls several records from db sorted in ASC/DESC order and filtered by some value:

    $sortingcriteria = 'id';
    $filter1 = 'free';
    $s = $modx->newQuery('Company');
    $s->sortby($sortingcriteria,'ASC');
    $s->where(array(
       'pay_type' => $filter1,
    ));
    $out = $modx->getCollection('Company',$s);
    $output = '';
    foreach ($out as $item) {
        $fields = $item->toArray();
        $output .= $modx->getChunk('showAllCompaniesTpl', $fields);
    }
    
    return $output;