Jump to content

[SOLVED] array_multisort with randomization


bespoke

Recommended Posts

Hello, all.  I've run into a nasty little problem and I'm wondering if any of you can offer any insight.

 

You see, I've got a array set up in a fashion similar to the following:

 

Name  |  Age

------------------

John    |  4

Jill        |  7

Mary    |  6

Harold |  4

Lou      |  4

Tom    |  6

 

This array changes its order every time the script is run.  So, one time we might have John at the top, and another time he might be in the middle.  Every name keeps the same age, however.

 

Now, what I want to do is sort the ages from oldest to youngest.  I can do that with this handy little function:

 

foreach ($childrenArray as $key => $row) {
    $sortedName[$key]  = $row[0];
    $sortedAge[$key] = $row[1];
}

array_multisort($sortedAge, SORT_DESC, $childrenArray);

 

So that works all right.  Jill goes to the top, and Harold, Lou, and John are always at the bottom.  My problem is that the names are ordered, as well as the ages.  Although I want them sorted by age, I do not want them sorted by name at all.  Since the multidimensional array is randomly ordered to begin with, I want to maintain a bit of uncertainty.  I.e., John and Harold will always be next to each other after the table is sorted, but I do not want John to always be above Harold, or vise versa.

 

I was hoping a sorting argument would be SORT_RAND, but, fie, one does not exist!

 

Any help would be greatly appreciated.  Thank you for your time.

Link to comment
Share on other sites

Thank you for your response, darkfreaks.  The code you provided orders my array by age, yes, but I'm getting the same problem, whether or not I use SORT_NUMERIC or SORT_DESC or SORT_ASC.

 

I want the ages to be ordered, and then randomized so the names aren't in the same place every time.  Does that make sense?

 

So one time I'd have this:

 

John4

Mark4

Aaron4

Gabe7

Tom8

Clark8

 

And another time I'd have this:

 

Mark4

John4

Aaron4

Gabe7

Clark8

Tom8

 

For some reason, whenever they're sorted by age, they're also sorted alphabetically by name!  I either need to know how to randomize the sorted array, while keeping the ages in numerical order, or simply not alphabetize the list at all, since the original array is always random.

 

Any suggestions?  Thanks in advance.

Link to comment
Share on other sites

try

<?php
$people = array (
            array('John',4),
            array('Jill',7),
            array('Mary',6),
            array('Harold',4),
            array('Lou',4),
            array('Tom',6)
);

function randsort ($a, $b)
{
    if ($a[1]==$b[1]) return rand(-1,1);
    return $a[1]>$b[1] ? -1:1;
}

usort ($people, 'randsort');

echo '<pre>', print_r($people, true), '</pre>';
?>

Link to comment
Share on other sites

Thank you both, darkfreaks and Barand.  Barand, I used your code, which worked flawlessly.  I'm not entirely sure how it works, so I'll have to do some research on your funny little symbols;  but the point is that it does work.  Thank you very, very much.

 

Both of you responded very quickly, and I thank you for allowing me to finish this project up tonight.

Link to comment
Share on other sites

hmmm well without knowing i wouldnt know where to start

<?php
$sortedName[$key]  = $row[0]; 

$sortedName[$key]= shuffle($sortedName[$key]);?>

 

I am getting the following error from your code:

 

Warning: shuffle() expects parameter 1 to be array, string

 

Do not worry too much about it, as the page is already working.  If you do come up with something that speeds the process up, though, I'll be ready to try it out.  Thanks again!

Link to comment
Share on other sites

Explanation

 

function randsort ($a, $b)
{
    if ($a[1]==$b[1]) return rand(-1,1);       // if equal, return -1, 0 or 1 at random
    return $a[1]>$b[1] ? -1:1;                   // otherwise sort descending
}

usort ($people, 'randsort');

 

When using usort() with a custom sort function (in this case randsort() ) each pair of array elements is passed to the function for comparison (as $a and $b).

 

The function should return 0 if the elements are considered equal, -1 if $a should sort above $b, 1 if $a should sort below $b.

 

In this case if equal it returns a random -1,0 or 1 to give random order when ages are the same.

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.