<p>Would be a lot cleaner/more efficient to do this from a custom plugin in PHP, but if you want to do it from a template, this should work:</p>

<pre><code>{% set entryArr = {} %}

{# Grab all of the entries in the section #}
{% set entries = craft.entries.section('news').find() %}

{# Loop through them generating a random number between 0 and the weight custom field #}
{% for entry in entries %}
    {% set entryArr = entryArr|merge({(entry.slug): random(range(0, entry.weight))}) %}
{% endfor %}

{# Sort the array by the ascending value maintaining the keys #}
{% set entryArr = entryArr|sort %}

{# print them off #}
&lt;ul&gt;
{% for slug, randomNumber in entryArr %}
    {% set entry = craft.entries.slug(slug).first() %}
    &lt;li&gt;{{ entry.title }} - Max Range: {{ entry.randomNumber }} - Random Number: {{ randomNumber }}
{% endfor %}
&lt;/ul&gt;
</code></pre>

CC BY-SA 4.0
2018-07-06T18:17:33.120Z
2018-07-06T18:17:33.120Z
Brad Bell
<p>I have a field in a channel called "weight" where the user can set a number between 0-1000. On page load I want to generate a random number between 0 and "weight" for each entry, and then sort the entries based on these numbers.</p>

<p>How can I do this with Craft 2/Twig?</p>

<random>
weighted random order
# weighted random order

(Asked by: username_0 on 2018-07-06)

I have a field in a channel called "weight" where the user can set a number between 0-1000. On page load I want to generate a random number between 0 and "weight" for each entry, and then sort the entries based on these numbers.

How can I do this with Craft 2/Twig?

**Tags:** random

---

## 1 answers

### Answer by username_1 on 2018-07-06. Score: 1 | Accepted answer

Would be a lot cleaner/more efficient to do this from a custom plugin in PHP, but if you want to do it from a template, this should work:
{% set entryArr = {} %}

{# Grab all of the entries in the section #}
{% set entries = craft.entries.section('news').find() %}

{# Loop through them generating a random number between 0 and the weight custom field #}
{% for entry in entries %}
    {% set entryArr = entryArr|merge({(entry.slug): random(range(0, entry.weight))}) %}
{% endfor %}

{# Sort the array by the ascending value maintaining the keys #}
{% set entryArr = entryArr|sort %}

{# print them off #}

{% for slug, randomNumber in entryArr %}
    {% set entry = craft.entries.slug(slug).first() %}
    {{ entry.title }} - Max Range: {{ entry.randomNumber }} - Random Number: {{ randomNumber }}
{% endfor %}


---

