多维数组排序



我有以下数组:

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
                 (
                  [value]=>6.5
                  [id] =>3
                  )
            )
        )
)

我想按id相等的值对数组进行排序,最好的方法是什么?

碰碰运气…

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

输出:

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
                )
        )
[...]

相关内容

  • 没有找到相关文章

最新更新