Page 1 of 1
sorting an array
Posted: Tue Oct 24, 2006 4:59 am
by malcolmboston
ok i have an array like this:
Code: Select all
$array['unique'][1] = 2;
$array['unique'][2] = 7;
$array['unique'][3] = 4;
$array['unique'][4] = 5;
$array['unique'][5] = 6;
$array['unique'][6] = 8;
and i want tor reorder the array so it goes DESC on the value so it would go
Code: Select all
$array['unique'][6] = 8;
$array['unique'][2] = 7;
$array['unique'][5] = 6;
$array['unique'][4] = 5;
$array['unique'][3] = 4;
$array['unique'][1] = 2;
how can this be achieved?
Posted: Tue Oct 24, 2006 5:10 am
by volka
Posted: Tue Oct 24, 2006 5:14 am
by malcolmboston
what if you have an array in this format?
Code: Select all
Array
(
[1] => Array
(
[date] => 1
[pageLoads] => 98
[unique] => 9
[firstTime] => 5
[returning] => 4
)
[2] => Array
(
[date] => 2
[pageLoads] => 170
[unique] => 72
[firstTime] => 66
[returning] => 6
)
[3] => Array
(
[date] => 3
[pageLoads] => 448
[unique] => 100
[firstTime] => 89
[returning] => 11
)
[4] => Array
(
[date] => 4
[pageLoads] => 472
[unique] => 179
[firstTime] => 173
[returning] => 6
)
Posted: Tue Oct 24, 2006 6:04 am
by volka
depends on how you want this array sorted.
But probably
http://de2.php.net/usort
Posted: Tue Oct 24, 2006 6:08 am
by malcolmboston
well i would like them ordered in the ordered of a certain value for eg DESC unique
see my first post for an example
sorting arrays has always been a pain in the ****
Posted: Tue Oct 24, 2006 6:31 am
by volka
yo, usort.
Write a function that compares two arrays by the value of the element
unique.
There are examples at
http://de2.php.net/usort
Posted: Tue Oct 24, 2006 7:32 am
by printf
array_multisort();
Code: Select all
<?
$array = array
(
1 => array
(
'date' => 1,
'pageLoads' => 98,
'unique' => 9,
'firstTime' => 5,
'returning' => 4
),
2 => array
(
'date' => 2,
'pageLoads' => 170,
'unique' => 72,
'firstTime' => 66,
'returning' => 6
),
3 => array
(
'date' => 3,
'pageLoads' => 448,
'unique' => 100,
'firstTime' => 89,
'returning' => 11
),
4 => array
(
'date' => 4,
'pageLoads' => 472,
'unique' => 179,
'firstTime' => 173,
'returning' => 6
)
);
// key to sort on...
$key = 'unique';
// type of sort (int, str)
$type = 'int';
// order of sort (asc, desc)
$order = 'desc';
// the array of key values to sort on
$sort = array ();
foreach ( $array AS $v )
{
$sort[] = $v[$key];
}
$type = ( $type == 'int' ? SORT_NUMERIC : SORT_STRING );
$order = ( $order == 'asc' ? SORT_ASC : SORT_DESC );
array_multisort ( $sort, $order, $type, $array );
print_r ( $array );
?>
pif!