user1072337
user1072337

Reputation: 12935

How to take two random entries from a multidimensional array in PHP

I am looking for a way to take a multidimensional array and choose 2 random entries from the top level to create a new multidimensional array.

For example, if I have an array $data that looks like the below:

array (size=3)
  0 => 
    array (size=1)
      0 => 
        object(stdClass)[500]
          public 'id' => int 2
          public 'first_name' => string 'Mary' (length=4)
          public 'last_name' => string 'Sweet' (length=5)
  1 => 
    array (size=1)
      0 => 
        object(stdClass)[501]
          public 'id' => int 9
          public 'first_name' => string 'Joe' (length=3)
          public 'last_name' => string 'Bob' (length=3)
  2 => 
    array (size=1)
      0 => 
        object(stdClass)[502]
          public 'id' => int 1
          public 'first_name' => string 'Shag' (length=4)
          public 'last_name' => string 'Well' (length=4)

How do I cut it up so that I take two of the three random entries, to get something like $data2:

array (size=2)
  0 => 
    array (size=1)
      0 => 
        object(stdClass)[500]
          public 'id' => int 2
          public 'first_name' => string 'Mary' (length=4)
          public 'last_name' => string 'Sweet' (length=5)
  1 => 
    array (size=1)
      0 => 
        object(stdClass)[502]
          public 'id' => int 1
          public 'first_name' => string 'Shag' (length=4)
          public 'last_name' => string 'Well' (length=4)

Upvotes: 1

Views: 66

Answers (1)

Mark Miller
Mark Miller

Reputation: 7447

Use array_rand(). You could get more sophisticated depending on what you are doing, but here is the basic idea:

$randkeys = array_rand($data, 2);
$data2 = array($data[$randkeys[0]], $data[$randkeys[1]]);

See demo

Upvotes: 3

Related Questions