Page 1 of 1

Storing info then sorting a multi-dimensional array

Posted: Mon Jan 31, 2005 2:54 am
by JayBird
i have created a simple search script for my site...nothing flashy.

Anyway. During the search, i store the number of matches for the serch term and the path to that page in an array. A sample of my array looks like this.

Code: Select all

Array
(
    ї0] => Array
        (
            їpath] => /data/web/_o/_c/_o/oconnordesign.co.uk/public/tsys/content/about/about_tsys.php
            їoccureneces] => 4
        )

    ї1] => Array
        (
            їpath] => /data/web/_o/_c/_o/oconnordesign.co.uk/public/tsys/content/about/global_operations.php
            їoccureneces] => 16
        )

    ї2] => Array
        (
            їpath] => /data/web/_o/_c/_o/oconnordesign.co.uk/public/tsys/content/about/in_europe.php
            їoccureneces] => 9
        )

    ї3] => Array
        (
            їpath] => /data/web/_o/_c/_o/oconnordesign.co.uk/public/tsys/content/benefits/benefits.php
            їoccureneces] => 5
        )

    ї4] => Array
        (
            їpath] => /data/web/_o/_c/_o/oconnordesign.co.uk/public/tsys/content/career_opportunities/career_opportunities.php
            їoccureneces] => 3
        )

    ї5] => Array
        (
            їpath] => /data/web/_o/_c/_o/oconnordesign.co.uk/public/tsys/content/contact/contact.php
            їoccureneces] => 4
        )

    ї6] => Array
        (
            їpath] => /data/web/_o/_c/_o/oconnordesign.co.uk/public/tsys/content/culture/history.php
            їoccureneces] => 8
        )
)
I need to be able to sort the array so the entry with the most number of occurences is first descending the the lowest number of occurences.

1) Am i storing the values in the best way?

2) How to sort the array on the value 'ocurrences'?

Thanks

Mark

Posted: Mon Jan 31, 2005 7:17 am
by feyd
usort() :)

Posted: Mon Jan 31, 2005 8:57 am
by JayBird
Thanks, but i really have no idea how to use that in my situation!? 8O

:?: :?:

Posted: Mon Jan 31, 2005 9:20 am
by feyd
I don't remember the exact return info, but it's the same as doing strcmp()

Code: Select all

function mySort($a, $b)
{
  if( $aї'occureneces'] > $bї'occureneces'] )
    return -1;
  elseif( $a&#1111;'occureneces'] < $b&#1111;'occureneces'] )
    return 1;
  else return strcmp( $a&#1111;'path'], $b&#1111;'path'] );
&#125;

usort( $array, 'mySort' );

Posted: Mon Jan 31, 2005 10:36 am
by JayBird
it bloody works!!!

Cheerz mate

Posted: Mon Jan 31, 2005 1:04 pm
by magicrobotmonkey
another, perhaps more efficient option would be to have an array like

Code: Select all

Array(
&#1111;path1] => occurences
&#1111;path2] => occurences

&#125;
that way you can use a simple sort on it and it may be easier to display.

Posted: Tue Feb 01, 2005 2:44 am
by JayBird
yes magicrobotmonkey, that is how i did have it, but i failed to mention there is actually going to be more info for each search result like page title etc.