Jump to content

PHP sorting


snaps11

Recommended Posts

Hello.  I have a multi dimensional array that needs to be sorted. Array  top25 [index][product id][number_of_purchases].  The index will contain a unique number for each product id. First product will be 1, second product will be 2, etc.  The product id will be a id number like 34324ac9a89.  The number of purchases will be how many times the item has been purchased. 

 

- End result:  I want to print the 25 most purchased products in this format.

 

product id - number of purchases

 

a39acz  -  503

a8cz9c  - 480

zc8ac  -  392

 

 

How do I do this?  Thanks

Link to comment
Share on other sites

Turn the index into a single dimension array that is keyed by the product id, with the number of purchases value.  You do not need the empty index, nor do you want it.  If when you are done with your sort, you want to recreate that you can do that easily enough by foreach() through the array to create a new one, where you can put in your ordinal value if you prefer, or just stay with the zero based index.  Hopefully this simple example illustrates, although I obviously left out a necessary for () loop to get the top 25 from the array by purchase.

 

        $r['a8cz9c'] = 480;
        $r['a39acz'] = 503;
        $r['zc8ac'] = 392;
        $r['fafefaef'] = 822;
        print_r($r);

        arsort($r, SORT_NUMERIC);
        print_r($r);

 

result:

 

Array
(
    [a8cz9c] => 480
    [a39acz] => 503
    [zc8ac] => 392
    [fafefaef] => 822
)
Array
(
    [fafefaef] => 822
    [a39acz] => 503
    [a8cz9c] => 480
    [zc8ac] => 392
)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.