How to shuffle this array within itself?

Asked

Viewed 65 times

2

$img = array
  (
  array("1.jpg","Logo","Tigre"),
  array("2.jpg","Logo","Cão"),
  array("3.jpg","Logo","Montanha"),
  array("4.jpg","banner","Design Grafico"),
  array("5.jpg","Logo","Dentista"),
  array("6.jpg","Logo","Basketball")
  );

I wanted the array to look like this

$img = array
  (
  array("5.jpg","Logo","Dentista"),
  array("1.jpg","Logo","Tigre"),
  array("4.jpg","banner","Design Grafico"),
  array("3.jpg","Logo","Montanha"),
  array("2.jpg","Logo","Cão"),
  array("6.jpg","Logo","Basketball")
  );

I tried this:

   function shuffle_assoc($list) { 
      if (!is_array($list)) return $list; 

      $keys = array_keys($list); 
      shuffle($keys); 
      $random = array(); 
      foreach ($keys as $key) { 
        $random[$key] = $list[$key]; 
      }
      return $random; 
    } 

    $img = array
      (
      array("1.jpg","Logo","Tigre"),
      array("2.jpg","Logo","Cão"),
      array("3.jpg","Logo","Montanha"),
      array("4.jpg","banner","Design Grafico"),
      array("5.jpg","Logo","Dentista"),
      array("6.jpg","Logo","Basketball")
      );
   $img = shuffle_assoc($img);
    print_r($img);
  • Thanks for the -1 but I still need xD help

  • 1

    $imagens[] = shuffle($img[0]) doesn’t do what you need?

  • is not working

  • I wanted to shuffle the position of the arrays but keeping the order of each "line"

1 answer

6


From what I’ve noticed there’s no pattern at all, so just use shuffle(...) must solve:

<?php

$img = array(
    array("1.jpg","Logo","Tigre"),
    array("2.jpg","Logo","Cão"),
    array("3.jpg","Logo","Montanha"),
    array("4.jpg","banner","Design Grafico"),
    array("5.jpg","Logo","Dentista"),
    array("6.jpg","Logo","Basketball")
);

echo 'Antes:', PHP_EOL;

var_dump($img);

shuffle($img);

echo 'Depois:', PHP_EOL;

var_dump($img);

See the result on ideone

Browser other questions tagged

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