1

I am using code igniter to retrieve data from a database

What is returned is an array objects

something like

array(
  [0] = {
    mobile => '027xxxxxx',
    id     => 1
  },
  [1] = {
    mobile => '027xxxxxx',
    id     => 4
  },
  [2] = {
    mobile => '027xxxxxx',
    id     => 5
  },
  [3] = {
    mobile => '027xxxxxx',
    id     => 7
  },
  [4] = {
    mobile => '027xxxxxx',
    id     => 9
  },
  [5] = {
    mobile => '027xxxxxx',
    id     => 10
  },
  [6] = {
    mobile => '027xxxxxx',
    id     => 112
  },
  [7] = {
    mobile => '027xxxxxx',
    id     => 113
  }
)

I have a variable called count, this contains an arbitrary number (although always less than the number of objects in the array).

My question is:

Say count = 3, How would I get an array of 3 random id's from the object?

something like array(4, 9, 1)

I only want to get a single id once

so array(4, 4, 9) would be incorrect.

Note that the id's are not linear.

1 Answer 1

4
$random_keys = array_rand(array_keys($your_array), 3);

array_rand

explain -

  • array_keys only return the key from the original array
  • array_rand will then pick randomly without repeatability
  • and the return of array is contains key to your original array
  • so you can retrieve any information from original array
Sign up to request clarification or add additional context in comments.

2 Comments

You won't believe how complicated I was going to make that ;)
@alreal: Awesome! @Zenph Same here!

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.