PHP array manipulation -- how to select an element and then shuffle remaining items
Basically, I need to add several random items from a PHP array to a choice that a user makes from that array. So for example, if the array is:
"kiwi, orange, pineapple, apple, grape, starfruit, kumquat"
and the user picks "pineapple" I want to choose X number of additional fruits from the remaining array items. The key thing is that "pineapple" can't be both the selection and also one of the additional fruits, so it needs to be excluded from the array once it's chosen as the selection.
Selection: pineapple
Your additional fruits: kiwi, grape, or开发者_如何学编程ange
NOT Selection: pineapple Your additional fruits: kiwi, pineapple, grape
I'm actually doing this with filenames, not fruits, but it seems easier to describe this way.
I think I can do the random selection part, but I'm not sure how to remove the item that's selected from the given array in PHP. Thanks very much for any suggestions or ideas.
If you don't know the exact position of the chosen item beforehand, use array_search() to find its index. unset() it from the array, then do your random selection.
Example
$key = array_search('pineapple', $fruits);
unset($fruits[$key]);
// Random selection here
If you know the index of pineapple, you could just unset it. This removes it from the array: unset($array[$index]);
You can remove elements (which are referenced using an integer eg $Array[5]) by using array_splice
array array_splice ( array &$input , int $offset [, int $length = 0 [, mixed $replacement ]] )
http://php.net/manual/en/function.array-splice.php
You can mix up an array using shuffle
bool shuffle ( array &$array )
http://php.net/manual/en/function.shuffle.php
This should do the job!
Another approach would be to use array_diff
to directly return an array which does not contain the chosen element(s), e.g.:
$theFruit = 'pineapple';
$remainder = array_diff($arr, array($theFruit));
//shuffle
shuffle($remainder);
// now do something with the first three from the shuffled remainder
print_r(array_slice($remainder, 0, 3));
精彩评论