TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Advanced PHP Programming (http://www.talkphp.com/advanced-php-programming/)
-   -   Array Sorting ! (http://www.talkphp.com/advanced-php-programming/5942-array-sorting.html)

maeltar 07-30-2011 01:37 PM

Array Sorting !
 
Am at my wits end here and am hoping there is a quick and easy solution....

I need to sort a multi dimentional array, the array is built as follows (abridged):
Code:

$i++;
$missed[$i] = array($row[3], $row[4], ($weeks - $num_rows));

so for example the data would look like :
Code:

$missed[0] = array(Fred, Smith, 3)
$missed[1] = array(Bert, Smith, 99)
$missed[2] = array(Gerty, Blogs, 22)

My problem is, how do I sort the array $missed on the last number in the array ?

Or, am I going about this in the wrong way ?

maeltar 07-30-2011 02:15 PM

Got it sorted... Bit more googling and found the following code..

Code:

function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    asort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}


tony 08-01-2011 04:38 AM

what about usort:

PHP Code:
usort($missed, function ($a, $b) {
  if ($a[2] == $b[2]) {
    return 0;
  }
  return ($a[2] < $b[2]) ? -1 : 1;
});

maeltar 08-01-2011 03:48 PM

Thanks Tony, thats one for the "code snippets" :D

Ok, next problem....

Code:

$missed[0] = array(Fred, Smith, 3)
$missed[1] = array(Bert, Smith, 52)
$missed[2] = array(Gerty, Blogs, 22)
$missed[3] = array(Fred, Blogs, 22)

How do I count the quantity of unique occurances of the last emement this the array, i.e.

Code:

$uniques[$i] = array("missed" => 22, "occurances" => 2)
There are around 35k records that I have to go through, so not enormous, and there can only be a max of 52 unique entries (by design), I'm just getting lost how to itterate through the arrays and count them correctly.. Any ideas ?

tony 08-01-2011 07:59 PM

you can use the the hash-table characteristic of arrays in your advantage here. For example:
PHP Code:
$uniques = array();
foreach($missed as $record) {
  $uniques[$record[2]] = empty($unique[$record[2]]) ? 0 : ($unique[$record[2] + 1);
}
At the en unique would have the the "missed" part as the key and the "occurrences" as the value in your example it would be like this:

PHP Code:
$uniques[22] = 2;

maeltar 08-02-2011 05:27 AM

You sir, are a god :D

tony 08-02-2011 12:51 PM

Glad it helped. I am not a god haha, if anything a sorcerer's apprentice :P


All times are GMT. The time now is 07:43 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0