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
  • 62,889
  • 9
  • 98
  • 100
Lizard
  • 39,504
  • 36
  • 102
  • 164
  • 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
  • 54,473
  • 20
  • 110
  • 156
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
  • 594,236
  • 102
  • 740
  • 814
0

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

usort  ( $arrayy  , callback $cmp_function  );
Thariama
  • 47,807
  • 11
  • 127
  • 149