我有一个多维数组,我想从中选择11个不同的单词。来自不同数组索引的每个单词。
这是数组链接:My multi-dimensional array
array (
'w' =>
array (
0 => 'walls',
1 => 'well',
2 => 'why',
),
'e' =>
array (
0 => 'end',
),
'a' =>
array (
0 => 'advantage',
1 => 'afford',
2 => 'affronting',
3 => 'again',
4 => 'agreeable',
5 => 'ask',
6 => 'at',
),
'c' =>
array (
0 => 'children',
1 => 'civil',
2 => 'continual',
)
);
我的欲望输出:
From w => well
From e => end
From a => again
and so on.
输出如: array(well, end, again, ...) as array.
答案 0 :(得分:1)
使用以下代码:
$f = array_keys($result); // grouping the indices, namely, the characters
$a = "";
for($c=0;$c<count($f);$c++){
$a .= $f[$c];
} // grouping the indices stored in array $f to a string, $a
$words = array();
for($c=0;$c<11;$c++){
$random = $a[rand(0,strlen($a)-1)];
$k = $result[$random];
// $k stores the array of the character index, stored in $result
$random2 = rand(0,count($k)-1);
$words[$c] = $k[$random2];
// choose a word from a given character array
$a = preg_replace("/".$random."/","",$a);
// remove the character from $a to prevent picking words which start with the same character
}
print_r($words);
我已经过测试,证明有效
答案 1 :(得分:0)
您可以使用array_rand()函数实现此功能:
<强> PHP 强>
$words = [];
$limit = 3; //Replace this with your limit, 11
$count = 0;
shuffle($array);
foreach($array as $key => $value) {
$words[] = $value[array_rand($value)];
$count++;
if ($limit == $count) {
break;
}
}
答案 2 :(得分:-1)
Check Online,请告诉我。
使用shuffle
和array_slice
即可获得所需内容。
shuffle
函数使您的数组随机,并从中array slice
切片11子数组。
数组切片有3个参数,第一个是数组,第二个是你想要开始的偏移量,最后一个是你需要切割的数量。
$words = array();
shuffle($result);
$res = array_slice($result, 0, 11);
foreach($res as $key => $value){
shuffle($value);
$words[] = $value[0];
}
print_r($words);