mercredi 3 janvier 2018

Select multiple random values by key from arrays

I want to select 5 random ID's from the arrays. Here is my array $test:

Array
(
    [id] => 13
    [pets] => 8
)
Array
(
    [id] => 15
    [pets] => 8
)
Array
(
    [id] => 16
    [pets] => 10
)
Array
(
    [id] => 17
    [pets] => 9
)
Array
(
    [id] => 18
    [pets] => 10
)
Array
(
    [id] => 19
    [pets] => 10
)
Array
(
    [id] => 20
    [pets] => 0
)
Array
(
    [id] => 21
    [pets] => 8
)
Array
(
    [id] => 22
    [pets] => 9
)
Array
(
    [id] => 23
    [pets] => 4
)
Array
(
    [id] => 24
    [pets] => 0
)
Array
(
    [id] => 40
    [pets] => 8
)
Array
(
    [id] => 43
    [pets] => 2
)

How can I select 5 random ID's from the array and put them into a string like this:

$ids = '13,17,18,21,43';

I've tried to use array_rand but it does not seem to work for my type of arrays. i'm not sure if there are any other built in PHP functions that can do this type of job or if I have to create my own function, It would be nice to have my own function like this to plug in the numbers. thanks




Aucun commentaire:

Enregistrer un commentaire