Forum Moderators: coopster

Message Too Old, No Replies

Array re-sorting

array sort

         

fengqysll

2:59 pm on Mar 2, 2009 (gmt 0)

10+ Year Member



Hi

I have a array as below:

$array = array(
array(0,0),
array(0,1),
array(0,1),
array(0,1),
array(2,2),
array(3,4),
array(1,0),
array(1,0),
array(4,3),
array(2,3),
array(2,2),
array(3,2)
);
I used method array_count_values to have the sorted array below:
Array
(
[0 - 0] => 1
[0 - 1] => 3
[1 - 0] => 2
[2 - 2] => 2
[2 - 3] => 1
[3 - 2] => 1
[3 - 4] => 1
[4 - 3] => 1
)

however, I would like to have the array looks like the one below:

Array
(
[0 - 0] => 1
[0 - 1] => 5
[2 - 2] => 2
[2 - 3] => 2
[3 - 4] => 2
)

because 0 -1 and 1 - 0 are the same results, same as the 2 - 3 and 3 - 2.

thanks for your help!

rob7591

8:08 pm on Mar 2, 2009 (gmt 0)

10+ Year Member



If you know each array is only going to have two elements, you can try something like this:

function my_array_count_vals($array) {
$return = array();

foreach ($array as $a) {
$min = min($a);
$max = max($a);
if ($return["$min - $max"])
$return["$min - $max"]++;
else
$return["$min - $max"] = 1;

return $return;
}

Haven't tested, but it should give you an idea..

fengqysll

9:04 am on Mar 3, 2009 (gmt 0)

10+ Year Member



To rob7591:

Thanks very much, problem solved, very interesting code, I will study your code. cheers

fengqysll

9:20 am on Mar 3, 2009 (gmt 0)

10+ Year Member



Thanks rob7591, your solution maybe the easiest ever, thank you so much