1

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)

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.