开发者

Multidimensional array sorting

开发者 https://www.devze.com 2023-03-20 13:09 出处:网络
I have the following array: array ( [0]=>array ( [0]=>array ( [value]=>3.5 [id] =>1 ) [1]=>array

I have the following array:

array
(
[0]=>array
        (
            [0]=>array
            (
                  [value]=>3.5
                  [id] =>1
                  )
                 [1]=>array
                 (
                  [value]=>1.5
                  [id] =>2
                  )
                 [2]=>array
                 (
                  [value]=>1.5
                  [id] =>3
                  )
            )
        )
[1]=>array
        (
            [0]=>array
            (
                  [value]=>4.5
                  [id] =>1
                  )
                 [1]=>array
                 (
                  [value]=>5.5
                  [id] =>2
                  )
                 [2]=>array
                 (
                 开发者_Go百科 [value]=>6.5
                  [id] =>3
                  )
            )
        )
)

I want to sort the array by value where the id is equal, what is the best way to do this?


Trying my luck…

<?php

$data = array(
    array( /* #1 */
        array('value' => 3.5, 'id' => 1),
        array('value' => 1.5, 'id' => 2),
        array('value' => 1.5, 'id' => 3)
    ),
    array( /* #2 */
        array('value' => 4.5, 'id' => 1),
        array('value' => 5.5, 'id' => 2),
        array('value' => 6.5, 'id' => 3)
    )
);

/* Merge #1 and #2 into one array */
$tmp = array();
foreach ($data as $firstDimension) {
    $tmp = array_merge($tmp, $firstDimension);
}

/* Sort by id (1st, ASC) and value (2nd, DESC) */
usort($tmp, function ($a, $b) {
    $d = $a['id'] - $b['id'];

    if ($d !== 0) {
        return $d;
    }

    return $b['value'] - $a['value'];
});

/* Group entries by id */
$grouped = array();
$c = 0;
foreach ($tmp as $entry) {
    if ($c > 0 && $grouped[$c - 1]['id'] === $entry['id']) {
        $grouped[$c - 1]['values'][] = $entry['value'];
    } else {
        $grouped[] = array('id'     => $entry['id'],
                           'values' => array($entry['value']));
        $c++;
    }
}
unset($tmp);

print_r($grouped);

Outputs:

Array
(
    [0] => Array
        (
            [id] => 1
            [values] => Array
                (
                    [0] => 4.5
                    [1] => 3.5
                )

        )

    [1] => Array
        (
            [id] => 2
            [values] => Array
                (
                    [0] => 5.5
                    [1] => 1.5
                )

        )
[...]
0

精彩评论

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