Get a subset of random values from an array php

前端 未结 2 1133
猫巷女王i
猫巷女王i 2021-01-14 18:53

Starting with an array with 10K values. I want to randomly get 1000 values from it and put them into another array.

Right now, I am using a for loop to get the valu

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-14 19:24

    You could use array_rand() to get multiple items ?

    $random_keys = array_rand($seedkeys, 1000);
    shuffle($random_keys);
    

    This will give you an array of random keys, so to get an array of values you need to do something like this:

    $result = array();
    foreach ($random_keys as $rand_key) {
        $result[] = $seedkeys[$rand_key];
    }
    

    You could instead use array_intersect_key():

    $result = array_intersect_key($seedkeys, array_flip($random_keys));
    

提交回复
热议问题