开发者

Arranging a multi-dimensional array

I have a PHP array that looks like this: http开发者_JAVA百科://pastie.org/1346063 (see pastie for array example)

What I want to do is re-sort that array into another array that is sorted by each array's [votes][POINTS] sub-array numerically descending. The array with the highest [votes][POINTS] value will be the first listed in the main array.


Using the usort() function we can create our own comparison function:

function cmp($a, $b) {
    if($a['votes']['POINTS'] == $b['votes']['POINTS']) {
        return 0;
    }
    return ($a['votes']['POINTS'] < $b['votes']['POINTS']) ? 1 : -1;
}

usort($array, 'cmp');

Results:

Using test data with a similar structure as yours:

Array
(
    [0] => Array
        (
            [votes] => Array
                (
                    [UP] => 1
                    [DOWN] => 0
                    [POINTS] => 5
                )

        )

    [1] => Array
        (
            [votes] => Array
                (
                    [UP] => 1
                    [DOWN] => 0
                    [POINTS] => 4
                )

        )

    [2] => Array
        (
            [votes] => Array
                (
                    [UP] => 1
                    [DOWN] => 0
                    [POINTS] => 2
                )

        )

    [3] => Array
        (
            [votes] => Array
                (
                    [UP] => 1
                    [DOWN] => 0
                    [POINTS] => 1
                )

        )

)


Solution:-

Suppose, your array is stored in a variable named $data

You can simply sort your multi-dimensional array with array_multisort

foreach ($data as $key => $row) {
    $points[$key]  = $row['votes']['points'];
}

// Sort the data with points descending
array_multisort($points, SORT_DESC, $data);

Hope this helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜