Answer the question
In order to leave comments, you need to log in
How to select a random value from storage using memcacheD in PHP (RANDOMKEY replacement for Redis)?
Hello.
I model the situation (which, as usual, cannot be radically changed). With the help of memcached (client Memcache d on PHP is used ), for example, quotes (text or even something binary, but in base64) are stored.
The keys are the quote numbers. Values — texts of quotes. The citation numbers are inconsistent. That is, at first they could add quotes with numbers 100 and 101, and then 18, 25 and 204, and there may not be other quotes at all. Quotes are thousands.
Not everything in the vault is quotes. In addition to quotes, there are several (very few - a few) other values \u200b\u200bin the repository, but their keys are known in advance .
Task: display a random quote from the repository.
Please tell me the most elegant solution with minimal redrawing of the existing economy.
Answer the question
In order to leave comments, you need to log in
In my opinion you have a big problem with the architecture.
But since you said that it is not possible to change the architecture, then, provided that the maximum value of the key is known, the variant can be like this (but it is super-non-optimal):
do {
$str = $m->get(rand(0,$max_key_number));
} while (!$str)
echo $str;
In any case, before choosing, you will have to “get” all the quote numbers and put them in some place (for example, in a subd or a regular PHP array, serialize it and write it to a file). Then, according to the situation:
1. If the values are stored in the subd, we do the usual sql-query ORDER BY RAND ()
2. If the values are stored in an array (for example, $ a):
$id = $a[mt_rand(0, count($a)-1]
It would be logical to store quotes by the keys of integers from 1 to N
In PHP, generate randomly from 1 to N and get the quote by key, I do this everywhere if something like this is needed.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question