mirror of
https://github.com/getgrav/grav.git
synced 2026-02-23 07:01:26 +01:00
Added new 'sort_by_key' twig filter which sorts an array by the desired key. It also takes in a direction as second argument which can be any of the predefined sorting flags (http://php.net/manual/en/array.constants.php)
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
<?php
|
||||
namespace Grav\Common;
|
||||
|
||||
use Grav\Component\Filesystem\ResourceLocator;
|
||||
|
||||
/**
|
||||
@@ -34,6 +35,7 @@ class TwigExtension extends \Twig_Extension
|
||||
new \Twig_SimpleFilter('truncate', array($this,'truncateFilter')),
|
||||
new \Twig_SimpleFilter('*ize', array($this,'inflectorFilter')),
|
||||
new \Twig_SimpleFilter('md5', array($this,'md5Filter')),
|
||||
new \Twig_SimpleFilter('sort_by_key', array($this,'sortByKeyFilter')),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -216,4 +218,25 @@ class TwigExtension extends \Twig_Extension
|
||||
|
||||
return $uri->rootUrl($domain) .'/'. $locator->findResource($input, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts a collection by key
|
||||
*
|
||||
* @param string $input
|
||||
* @param string $filter
|
||||
* @param string $direction
|
||||
* @return string
|
||||
*/
|
||||
public function sortByKeyFilter(&$input, $filter, $direction = SORT_ASC)
|
||||
{
|
||||
$output = [];
|
||||
|
||||
foreach ($input as $key => $row) {
|
||||
$output[$key] = $row[$filter];
|
||||
}
|
||||
|
||||
array_multisort($output, $direction, $input);
|
||||
|
||||
return $input;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user