Arranging a multi-dimensional array

廉价感情. 提交于 2020-01-04 11:09:12

问题


I have a PHP array that looks like this: http://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.


回答1:


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
                )

        )

)



回答2:


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.



来源:https://stackoverflow.com/questions/4351209/arranging-a-multi-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!