Answers.Body: <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>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-07-06T18:17:33.120Z
Answers.LastActivityDate: 2018-07-06T18:17:33.120Z
Answers.UserDisplayName: Brad Bell
Body: <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>
  
Tags: <random>
Title: weighted random order
ThreadText: # 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 #}
  <ul>
  {% for slug, randomNumber in entryArr %}
      {% set entry = craft.entries.slug(slug).first() %}
      <li>{{ entry.title }} - Max Range: {{ entry.randomNumber }} - Random Number: {{ randomNumber }}
  {% endfor %}
  </ul>
  
  ```
  
  
  ---
  
  