CakePHP

How to sort array in View by using Set::sort() in CakePHP

You can sort array at the time of fetching data by using order in Model find function, but in case due to any  reason if you could not get the array in desired order then you can sort the same in view file also by using Set::sort()

Suppose below standard CakepPHP $employee array you have got from Model by belongsTo relation

Array
(
    [0] => Array
        (
            [Person] => Array
                (
                    [id] => 1
                    [department_id] => 2
                    [name] => Harsh Singh
                    [birth_date] => 1988-08-21
                )

            [Department] => Array
                (
                    [id] => 2
                    [name] => Computer
                )

        )

    [1] => Array
        (
            [Person] => Array
                (
                    [id] => 2
                    [depatment_id] => 1
                    [name] => Rajeev Rai
                    [birth_date] => 1882-07-10
                )

            [Department] => Array
                (
                    [id] => 1
                    [name] => Administration
                )

        )

    [2] => Array
        (
            [Person] => Array
                (
                    [id] => 3
                    [department_id] => 3
                    [name] => Vinay Singh
                    [birth_date] => 1966-052-09
                )

            [Department] => Array
                (
                    [id] => 3
                    [name] => Management
                )

        )

)

Default Order:

We can see the data below in a nice tabular format .

Employee.id Employee.name Employee.birth_date Department.id Department.name
1 Harsh Singh 1988-08-21 2 Computer
2 Rajeev Rai 1882-07-10 1 Administration
3 Vinay Singh 1966-05-09 3 Management

Set::sort() takes three parameters, the array to sort, the array key to sort on and the sort order.

Now we are using Set::sort() to sort above array.

$sortedEmployee = Set::sort($employee, ‘{n}.Person.birth_date’, ‘asc’);

We can see the sorted array as below,

Employee.id Employee.name Employee.birth_date Department.id Department.name
3 Vinay Singh 1966-05-09 3 Management
2 Rajeev Rai 1882-07-10 1 Administration
1 Harsh Singh 1988-08-21 2 Computer

in Set::sort($employee, ‘{n}.Person.birth_date’, ‘asc’), {n} means numeric. You can use {s} if key is string type.

In the table below, you can see which options are available.

Expression Definition
{n} Represents a numeric key
{s} Represents a string
Foo Any string (without enclosing brackets) is treated like a string literal.
{[a-z]+} Any string enclosed in brackets (besides {n} and {s}) is interpreted as a regular expression.

Comment here