Printing items from an associative array randomly

Asked

Viewed 45 times

0

I’m creating a carousel, where there will be 3 sliders containing 15 images inside each, totaling 45 images.

matriz

I created a array associative to display these images randomly, so far so good, however, now I need the first 15 items to be fixed, where I can choose which indexes are displayed first and the other 30 are displayed randomly but without repeating those 15 that I chose.

$clientes = array(
array(
    "nome" => "Cliente 1",
    "categoria" => "Turismo",
    "logo" => "turismo.jpg"
),
array(
    "nome" => "Suporte",
    "categoria" => "Tecnologia",
    "logo" => "suporte.jpg"
),
array(
    "nome" => "Faculdade Futura",
    "categoria" => "Educação",
    "logo" => "faculdade-futura.jpg"
),

shuffle($clientes);
foreach (array_slice($clientes, 0, 45) as $atributo => $valor):
   echo "{$valor["nome"]}";
endforeach;
);

That one of mine array has more than 60 items, where it is displayed in another part of the site, but in the carousel only need 45, so I used the array_slice().

1 answer

1

If I understand correctly I imagine this works:

$tmp = $clientes;
shuffle(array_slice(tmp, 15, 30));
$novo = array_merge(array_slice($clientes, 0, 15), $tmp);
foreach ($novo as $atributo => $valor):
   echo "{$valor["nome"]}\n";
endforeach;

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I only shuffled from the sixteenth item picking up 30 (I may not have understood that part, I may need all the elements except 15, if that’s what I can change the answer) items and concatenated with the 15 uneven initials.

Maybe this is it (I change if the AP clarifies):

$tmp = $clientes;
shuffle(array_slice(tmp, 15, count($clientes) - 15));
$novo = array_merge(array_slice($clientes, 0, 15), array_slice($tmp, 0, 30));
foreach ($novo as $atributo => $valor):
   echo "{$valor["nome"]}\n";
endforeach;

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I’m sorry if I ended up causing a confusion rs Actually the first 15 that will be fixed I will choose, now how will I choose is that I do not know, I think the easiest way is by the index, or else create an attribute.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.