我有一个array
,其中包含40
这样的元素
$i = array('1','2','3','4','5','6','7','8','9','10','11',
'12','13','14','15','16','17','18','19','20','21','22','23','24',
'25','26','27','28','29','30','31','32','33','34','35',
'36','37','38','39','40');
现在我有4
个5%, 10%, 15%, 20%
要求是我需要在减去所需的array values
后随机选择variation
。
假设我使用了5%
变体,因此我需要将5%
与数组分开,即2
元素,我需要从数组中随机删除并保留其余38
随机的新array
中的元素。因此,array
以及减去的元素都必须位于两个不同的array
中。
我需要一个带有两个参数的函数,一个是variation
,另一个是array
,即结果array
或减去元素array
。
所有其他变体都遵循相同的顺序。
答案 0 :(得分:0)
虽然我不确定 rest 38元素在一个新数组中随机是什么意思,例如这是否意味着新阵列也被洗牌?这就是我想出来的。
<?php
function splitArray($variation, $array) {
$count = count($array); // Count the elements in the given array
$removeNumber = floor($count*($variation/100)); // Calculate the number of elements to remove
// Create an array holding the index numbers for splicing, these numbers are random.
for($i=0; $i<$removeNumber; $i++) {
$removeArray[] = rand(0,$count-1);
}
// Loop through the removeArray to retrieve the indexes to splice at.
for($i=0; $i<count($removeArray); $i++) {
$subArray[] = $array[$removeArray[$i]];
array_splice($array, $removeArray[$i], 1);
}
// return the newly spliced array and the spliced items array
return array($array, $subArray);
}
$oldArray = array('1','2','3','4','5','6','7','8','9','10','11',
'12','13','14','15','16','17','18','19','20','21','22','23','24',
'25','26','27','28','29','30','31','32','33','34','35',
'36','37','38','39','40');
$array = splitArray(5, $oldArray);
$subArray = $array[0];
$newArray = $array[1];
答案 1 :(得分:0)
<?php
function subtractFromArray($array,$percentage){
//Randonmising the array
shuffle($array);
//percentage numeric equivalent wrt array aize
$substract_variation_count = floor(sizeof($array) * $percentage/100);
//New extracted array
$new_array = array_slice($array,$substract_variation_count);
//retuns the new array with 38 elements
return $new_array;
}
//array with all elements
$array = array('1','2','3','4','5','6','7','8','9','10','11',
'12','13','14','15','16','17','18','19','20','21','22','23','24',
'25','26','27','28','29','30','31','32','33','34','35',
'36','37','38','39','40');
//get new array
$new_array = subtractFromArray($array,5);
//print new array
print_r($new_array);
//Substracted array with 2 elements
$substrcated_array = array_diff($array,$new_array);
print_r($substrcated_array);
?>