M
M
Makfroy2020-02-11 09:18:06
PHP
Makfroy, 2020-02-11 09:18:06

How to organize the output randomly?

Hello, I have two chunks with blocks:
1) $lib.block.profile.3
2) $lib.block.profile.7

I need to display them in the template, only that each time they visit the page, they change places.
I have a snippet that I display in a template, now it looks like this:

<?php

$output = 'lib.block.profile.7';
if ($modx->resource->id==54) {
  $output = 'lib.block.profile.3';
}

return $modx->getChunk($output);


What is the condition for random output?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Kim, 2020-02-11
@kimono

$output = random_int(0, 1) ? 'lib.block.profile.7' : 'lib.block.profile.3';

D
Dmitry, 2020-02-11
@i__dmitry

// Список чанков оформляется в массив
$chunks = [
    'lib.block.profile.7',
    'lib.block.profile.3',
];
if ($modx->resource->id==54) {
    $output = $chunks[1]; // Не знаю, нужно ли вам это условие
} else {
    // Но если оно не выполняется, в $output кладется случайное значение чанка из массива
    $output = $chunks[rand(0, count($chunks) - 1)];
}
// Возвращается обработанный чанк
return $modx->getChunk($output);

G
granty, 2020-02-11
@granty

You need to display them in the template, only that each time you visit the page, they change places

If you need to swap places - random is not quite suitable. It is necessary to plant a cookie for the visitor, by which it will be clear what order of blocks was during the previous visit. Change the order of blocks, and when displaying the page, set the cookie again with this order of blocks. Then the blocks will be exactly swapped.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question