Let's say there is an array with 20 different values. I want to pick only 5 random values out of them. This is easy. I want to make sure that there are no duplicates in the results. That's no problem either - array_unique will do that job.
*But*... array_unique simple removes the duplicate value which means there are only 4 values in the result set. What I want it to do is this:
If there is a duplicate, remove it *and* replace it with another unique random value from the remaining 15 values.
How can this be done?
Thanks!
Tomas
[SOLVED] array_unique - always unique random values?
Moderator: General Moderators
-
tomfra
- Forum Contributor
- Posts: 126
- Joined: Wed Jun 23, 2004 12:56 pm
- Location: Prague, Czech Republic
[SOLVED] array_unique - always unique random values?
Last edited by tomfra on Sat Aug 14, 2004 8:42 am, edited 2 times in total.
- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
it's fairly easily done..
something like that...
Code: Select all
<?php
for($x = 0, $y = min( 5, sizeof( $array ) ); $x < $y; $x++)
$newarray[] = array_slice( $array, mt_rand(0, sizeof( $array ) - 1 ), 1);
?>-
tomfra
- Forum Contributor
- Posts: 126
- Joined: Wed Jun 23, 2004 12:56 pm
- Location: Prague, Czech Republic
It doesn't seem to work any better than what I used before because the last set of results has different number of results than the other ones. I probably used wrong example - let's say there are 77 values in the array and I need 5 unique random results in each result set. 20 can be easily divided into 4 result sets but 77 can't if you want to have 5 results in each of them.
That's why I don't think array_slice is a good choice.
Tomas
That's why I don't think array_slice is a good choice.
Tomas
-
tomfra
- Forum Contributor
- Posts: 126
- Joined: Wed Jun 23, 2004 12:56 pm
- Location: Prague, Czech Republic
Because the slice problem happened only on the 'last page' which did not have the same number of values as the other results sets, I solved it by creating another slice with the remaining number of values which I took from the beginning of the original array using array_merge.
Thanks for the help!
Tomas
Thanks for the help!
Tomas