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:
Djamil Legato
2014-09-24 15:50:21 -07:00
parent 00ac1da29d
commit eaa05ee252

View File

@@ -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;
}
}