views:

38

answers:

3

I have the following array, it is currently created sorted by entity_count (outputted by a query done in cakephp - I only wanted the top few entities), I want to now sort the array for the Entity->title.

I tried doing this with array_multisort but failed. Is this possible?

Array
(
    [0] => Array
        (
            [Entity] => Array
                (
                    [title] => Orange
                )

            [0] => Array
                (
                    [entitycount] => 76
                )

        )

    [1] => Array
        (
            [Entity] => Array
                (
                    [title] => Apple
                )

            [0] => Array
                (
                    [entitycount] => 78
                )
        )
    [2] => Array
        (
            [Entity] => Array
                (
                    [title] => Lemon
                )

            [0] => Array
                (
                    [entitycount] => 85
                )
        )
)
A: 

Try this:

$keys = array_map($arr, function($val) { return $val['Entity']['title']; });
array_multisort($keys, $arr);

Here array_map and an anonymous function (available since PHP 5.3, you can use create_function in prior versions) is used to get an array of the titles that is then used to sort the array according to their titles.

Gumbo
This is for PHP 5.3 only, and also Entity is not an object.
RobertPitt
A: 

You need to write a custom compare function and then use usort . Calll it using:

usort  ( $arrayy  , callback $cmp_function  );
Thariama
+1  A: 

Create a callback function like so:

function callback($value)
{
    return isset($value['entity']['title']) ? $value['entity']['title'] : null;
}

Then run it thew an array_map and multi sort

array_multisort(array_map($myArray,'callback'), $myArray);
RobertPitt
Thanks this worked great!
Lizard