A
A
advancesss2019-10-09 09:54:16
1C-Bitrix
advancesss, 2019-10-09 09:54:16

How to output foreach arResult randomly Bitrix?

Hello, this code displays a list of elements with a limit of 5 items. But the elements are displayed in a strict sequence (as far as I understand, sorting by date - first -> last - in my opinion this is the default sorting). How can I display a list of items in random order?

<?$counter = 0;?>
  <?foreach($arResult["ITEMS"] as $arItem):?>
  
   <?if($counter >= 5){break;}?>
  <h1><?=$arItem["NAME"]?></h1>
   <?$counter++?>
  <?endforeach;?>

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander, 2019-10-09
Madzhugin @Suntechnic

Another option is to immediately randomly select 5 elements from the database and display them in a loop in a row. For a regular component in Bitrix, something like:

'SORT_BY1' => 'RAND',
'SORT_ORDER1' => 'RAND',
'NEWS_COUNT' => 5,

A
Anton, 2019-10-09
@Eridani

array_rand

A
aby125, 2019-10-11
@aby125

As I understand it, it is necessary to output in the foreach itself in a random order? The matter is that it is possible to make selection from a database in a random order. But if you need it in the foreach itself, then try this:

<?$counter = 0;
$ar_keys = range(0, count($arResult["ITEMS"])-1);
shuffle($ar_keys);?>
<?foreach($ar_keys as $key):?>

  <?if($counter >= 5){break;}?>
  <h1><?=$arResult["ITEMS"][$key]["NAME"]?></h1>
  <?$counter++?>
<?endforeach;?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question