Paste the file in app/Utility/ArraySort.php
Remember, the file must be in app/Utility
folder
Call utility with App::uses like this
App::uses('ArraySort', 'Utility');
And sort arrays with magic methods field ArraySort::by<FieldName>()
as camelCase like ArraySort::byFirstName()
or ArraySort::byAge()
Examples:
<?php
$users = array(
array(
'id' => '1',
'first_name' => 'Renato',
'secondName' => 'Ribeiro',
'age' => '18',
),
array(
'id' => '3',
'first_name' => 'Beltrano',
'secondName' => 'Ribeiro',
'age' => '21',
),
array(
'id' => '4',
'first_name' => 'Fulano',
'secondName' => 'Ribeiro',
'age' => '20',
),
array(
'id' => '2',
'first_name' => 'Bar',
'secondName' => 'Foo',
'age' => '10',
)
);
$sorted = ArraySort::byFirstName($users); //will sort by first_name
print_r($sorted);
Always parse passed field to the snake_case FirstName => first_name SecondName => second_name Age => age etc.
To change it, pass an identifier to the second parameter
$sorted = ArraySort::bySecondName($users, ArraySort::CAMEL); //will sort by secondName
or
$sorted = ArraySort::bysecondName($users, false); //will sort by secondName
Identifier example if method is bySecondName()
ArraySort::SNAKE
=>second_name
(default)ArraySort::NORMAL
=>SecondName
(equals false)ArraySort::SNAKE_UWORDS
=>Second_Name
ArraySort::SNAKE_UFIRST
=>Second_name
ArraySort::CAMEL
=>secondName
ArraySort::CAMEL_UFIRST
=>SecondName
(equal to the NORMAL is a coincidence)ArraySort::HUMAN
=>Second Name
ArraySort::UPPERCASE
=>SECONDNAME
ArraySort::LOWERCASE
=>secondname
Identifier example if method is bysecondName()
ArraySort::SNAKE
=>second_name
ArraySort::NORMAL
=>secondName
ArraySort::CAMEL_UFIRST
=>SecondName