Sorting

Sorting is something we all need to do from time to time. Since there aren’t any really good options for the functions listed below, we decided to make it into a Cuisine Class.

The Sort class is a Utility which basically means you can address all methods as static functions, without using a wrapper of Facade. To use the Sort class, include the class and namespace at the top of your php document:

use Cuisine\Utilities\Sortw


##Sorting by Field

If you have an nested array of other arrays or objects, you can sort that array with this function on a certain field available in all of the sub-arrays.

Here’s an example:

$fruit = array(

	array(
		'name'		=>	'Apple',
		'country'	=>	'France',
		'harvest'	=>	'5-5-2016'
	),
	array(
		'name'		=>	'Pear',
		'country'	=>	'France',
		'harvest'	=>	'27-3-2016'
	),
	array(
		'name'		=> 	'Strawberries',
		'country'	=>	'The Netherlands',
		'harvest'	=>	'2-6-2016'
	),
	array(
		'name'		=>	'Peaches',
		'country'	=>	'Italy',
		'harvest'	=>	'14-9-2-16'
	)
);

Sort::byField( $fruit, 'harvest', 'ASC' );

The example above lists an array of fruit with which we’ll be doing all our examples. It then calls Sort::byField() on the $fruit-array and tells the function to use the harvest key and sort everything in an ascending matter.

Let’s break it down: >Sort::byField() sorts an array of arrays by a field.

> >The parameters passed down to the byField are, in order of appearence: > >* Data > The array of arrays you’d wish to sort. > >* Field > The key of the field you’d wish to sort on > >* Order (optional) > The order to sort on. Can be ‘DESC’ or ‘ASC’, defaults to ‘ASC’ >


##Plucking

Plucking an array fetches certain fields from a multi-dimensional array and puts them in a new array. So, working with the $fruit array mentioned above, the following code would be a good example of plucking:

Sort::pluck( $fruit, 'name' );
//returns array( 'Apple', 'Pear', 'Strawberries', 'Peaches' );

Here is a break it down: >Sort::pluck() Accepts an array, and returns an array of values from that array as specified by $field..

> >The parameters passed down to the pluck are, in order of appearence: > >* Data > The array of arrays you’d wish to pluck. > >* Field > The key of the field you’d wish to pluck on > >* Preserve keys - boolean (optional) > Whether or not to preserve the array keys. Defaults to true > >* Remove no matches - boolean (optional) > If the field doesn’t appear to be set, remove it from the output-array. > Defaults to true >