1

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
                )
        )
)
Sven
  • 69,403
  • 10
  • 107
  • 109
Lizard
  • 43,732
  • 39
  • 106
  • 167
  • possible duplicate of [How do I sort a multidimensional array in php](http://stackoverflow.com/questions/96759/how-do-i-sort-a-multidimensional-array-in-php) – Daniel Vandersluis Sep 27 '10 at 15:16

3 Answers3

3

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
  • 56,863
  • 21
  • 114
  • 161
0

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
  • 643,351
  • 109
  • 780
  • 844
0

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

usort  ( $arrayy  , callback $cmp_function  );
Thariama
  • 50,002
  • 13
  • 138
  • 166