Rand () php randomly the number suggested for ModX

Good afternoon. There are 3 numbers, for example (20, 125, 25) You need to run a random number to get one of these numbers

I have a call to getResources

[[!getResources? 
            &showHidden=`1` 
            &sortbyTV=`price`
            &sortdirTV=`ASC`
            &sortbyTVType=`integer`
            &tpl=`items` 
            &limit=`4` 
            &includeContent=`1` 
            &processTVs=`1` 
            &includeTVs=`image,tags,price` 
            &parents=`20,125,25`
        ]]

It is necessary to output one of the resources randomly instead of &parents

Author: Kamil NHOT, 2018-01-24

2 answers

$arrNumb = array(20,125,25);
$randNumb = $arrNumb[rand(0,2)];
 2
Author: Node_pro, 2018-01-24 11:35:12

In general, there are 2 options: simple, simple(but more difficult) -

Plain: Creating a randomItems snippet:

$items = array(20,132,21,125,22,23,117,25,142,24);

return $items[rand(0,9)];

Disadvantages:The client (manager) will have to go to the snippet in order to change the called resources (collections whose elements are displayed on the page)

Calling the snippet:

[[!getResources? 
            &showHidden=`1` 
            &sortbyTV=`price`
            &sortdirTV=`ASC`
            &sortbyTVType=`integer`
            &tpl=`items` 
            &limit=`4` 
            &includeContent=`1` 
            &processTVs=`1` 
            &includeTVs=`image,tags,price` 
            &parents=`[[randomItems]]`
]]

Harder

$items = explode(",",$items);

for ($i=0; $i <count($items) ; $i++)
{
    $items[i] *= 1;
}

return $items[rand(0,count($items) - 1)];

Here we accept an array of strings from a chunk (or template, or whatever). The explode is divided into an array of strings with a separator ",". So we use a loop to convert strings to numbers and retract the random number.

Calling the snippet:

[[!getResources? 
            &showHidden=`1` 
            &sortbyTV=`price`
            &sortdirTV=`ASC`
            &sortbyTVType=`integer`
            &tpl=`items` 
            &limit=`4` 
            &includeContent=`1` 
            &processTVs=`1` 
            &includeTVs=`image,tags,price` 
            &parents=`[[!randomItems? &items=`20,132,21,125,22,23,117,25,142,24`]]`
        ]]

Do not forget the exclamation mark (!), so that the elements are not cached and always display different elements

 0
Author: Kamil NHOT, 2018-01-25 11:54:53