如何在 php 中的关联数组中 select 随机值

How to select random value in an associate array in php

我有一个从 mysql 数据库中得到的数据(关联数组),看起来像这样

$data=[
    ["id"=>"1", "words"=>"words 1"],
    ["id"=>"2", "words"=>"words 2"],
    ["id"=>"3", "words"=>"words 3"],
    ["id"=>"4", "words"=>"words 4"],
    ["id"=>"5", "words"=>"words 5"],
    ["id"=>"6", "words"=>"words 6"],
    ["id"=>"7", "words"=>"words 7"],
    ["id"=>"8", "words"=>"words 8"],
    ["id"=>"9", "words"=>"words 9"],
    ["id"=>"10", "words"=>"words 10"]
];

现在我想形成一个新数组,其中仅包含来自该数组的 3 个随机数组 ($data),但我做不到,我正在使用的函数不起作用

下面是我的代码

$count="3";
$rand = array_intersect_key($array, array_flip(array_rand($array, $count)))

我希望新数组看起来像这样

$new_data=[
    ["id"=>"1", "words"=>"words 1"],
    ["id"=>"2", "words"=>"words 2"],
    ["id"=>"3", "words"=>"words 3"]
];

其中数组是随机选择的,而不仅仅是 1, 2, 3

请问我怎样才能做到这一点,我做错了什么

Actually your source data works exactly as you request -- Have you just made a typo with $data array and the reference value in $rand being $array when it should be $data?


尝试使用数组随机播放,然后将数组切片为仅 X 数字长。请注意,使用此方法不会保留原始外部数组键(数字),而使用您的原始工作版本会保留它们。

$count = 3; // how many array rows do you want to keep?
$newData = $data; // source array.
shuffle($newData);  // reorder the array. 
$newData = array_slice($newData,0,$count); // cut off after $count elements.

Please note that PHP shuffle is not suitable for any cryptographic randomness.

PHP shuffle() Documentation

PHP array_slice() Documentation