开发者

Sorting Mulitdemensional Array PHP

开发者 https://www.devze.com 2023-01-17 14:39 出处:网络
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->tit

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
               开发者_JAVA百科 (
                    [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
                )
        )
)


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);


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.


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

usort  ( $arrayy  , callback $cmp_function  );
0

精彩评论

暂无评论...
验证码 换一张
取 消