php - Twig shuffled array including duplicates when it shouldn't -
i have simple array of values. need output "random" subset of contents without duplications. however, i've got far including duplicates.
the server not have twig array extension installed don't have access shuffle filter.
oh, , if there's better approach, i'm open suggestions.
{% set arrimgs = {'0':'a','1':'b','2':'c','3':'d','4':'e','5':'f','6':'g','7':'h'} %} {% set outputqty = 5 %} {% set randomizedarr = [] %} {# create new array of randomly selected elements (just shuffle order) , limit result outputqty #} {% in 0..100 if randomizedarr|length < outputqty %} {% set tmpimg = [random(arrimgs)] %} {% if tmpimg not in randomizedarr %} {% set randomizedarr = randomizedarr|merge(tmpimg) %} {% endif %} {% endfor %} {% img in randomizedarr %} {{ img }}, {% endfor %}
as there extension this, suggest installing if @ possible. of course, assume have done if was.
your code doesn't quite work is, work couple of key tweeks.
{% set arrimgs = {'0':'a','1':'b','2':'c','3':'d','4':'e','5':'f','6':'g','7':'h'} %} {% set outputqty = 5 %} {% set randomizedarr = [] %} {# create new array of randomly selected elements (just shuffle order) , limit result outputqty #} {% in 0..100 if outputqty < arrimgs|length , randomizedarr|length < outputqty %} {% set tmpimg = random(arrimgs) %} {% if tmpimg not in randomizedarr %} {% set randomizedarr = randomizedarr|merge([tmpimg]) %} {% endif %} {% endfor %} {% img in randomizedarr %} {{ img }}, {% endfor %}
notice have added check in for
loop make sure don't create infinite loop requesting more unique items arrimgs
array can provide. also, check not working because randomizedarr
never contains items hashes , set
ing tmpimg
hash containing item picked arrimgs
. moving transformation has actual merge
call, issue solved.
Comments
Post a Comment