0

Possible Duplicate:
How do I sort a multidimensional array in php

i need to sort and merge a complicated array! array is multidimensional and sub arrays use 2 key/values like this:

<?php
$result = array(
array("1", "20"),
array("1", "33"),
array("2", "10"),
array("2", "25"),
array("2", "7"),
array("3", "33"),
array("3", "80"),
array("4", "300")
);
print_r($result);
?>

now i need to sort it based on aggregation of key[1] values (in sub-arrays) where values of keys[0] is similar and merge then sort it from more to less! for example in above i like result to be:

Array
(
    [0] => Array
        (
            [0] => 4
            [1] => 300
        )

    [1] => Array
        (
            [0] => 3
            [1] => 113
        )

    [2] => Array
        (
            [0] => 1
            [1] => 53
        )

    [3] => Array
        (
            [0] => 2
            [1] => 42
        )

)

i hope my explanation is clear enough.

Community
  • 1
  • 1
Vahid
  • 362
  • 1
  • 5
  • 19
  • 1
    i was read all of them! this is not like my problem, why you just take negative point on questions!? i'm afraid to make a question in this SO :) – Vahid Oct 16 '12 at 21:28
  • Right, you first need to divide your problem. The one part is to do the aggregation and the second part is to do the sort. But both really has been covered. – hakre Oct 16 '12 at 21:50
  • maybe you are right, i'm not good enough in arrays, i searched every where to solve it myself, but i couldn't! – Vahid Oct 16 '12 at 21:57

2 Answers2

1

The key here is the array_multisort function, but it requires some work to get the input in the right format. Have a look at the code below. First we accumulate the values, then split it in an index array and a value array, sort it with multisort and merge it back together.

$result2 = array();
foreach($result as $pair) {
    if  (!isset($result2[$pair[0]]))
        $result2[$pair[0]] = 0;
    $result2[$pair[0]] += $pair[1];
}
$array1 = array();
$array2 = array();
foreach($result2 as $key => $value) {
    array_push($array1, $key);
    array_push($array2, $value);
}
array_multisort($array2, SORT_DESC, $array1);
$result3 = array();
for ($i = 0; $i < count($array1); $i++) {
    array_push($result3, array($array1[$i], $array2[$i]));
}
print_r($result3);
Joost
  • 3,824
  • 3
  • 24
  • 47
0

In your specific case, you can compact the two operations (aggregate sums, create the sort array) into one iteration.

However the code becomes hard to read:

list($sort, $result) = array_reduce($result, function($a, $v) {
    $a[1][$v[0]] = [$v[0], (@$a[0][$v[0]] += $v[1])];
    return $a;
}, []);

array_multisort($sort, SORT_NUMERIC, SORT_DESC, $result);
hakre
  • 178,314
  • 47
  • 389
  • 754