开发者

Arranging a multi-dimensional array

开发者 https://www.devze.com 2023-01-28 23:58 出处:网络
I have a PHP array that looks like this: http开发者_JAVA百科://pastie.org/1346063 (see pastie for array example)

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

精彩评论

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