首页 > 解决方案 > PHP 通过 2 个值生成数组

问题描述

我有 2 个值:值 1 = 423749 值 2 = 328493

值 1 = 20% 值 2 = 80%(值 1 - 100% 的剩余部分)

 $Array_Generator = array(
  'Max_Values'   => 200,
  'Values'       => array(
   'Value_1'      => array(
    'Value'        => 423749,
    'Percent'      => 20, // %
   ),
   'Value_2'      => array(
    'Value'        => 328493,
    'Percent'      => 80, // %
   ),
  ),
 );

按最大数组值 = 200

我需要一个 PHP 能够生成一个包含 200 个值且值 1 = 20% 的数组并包含在数组示例中的随机位置

价值 1 价值 2 价值 2 价值 1 价值 2 价值 2 价值 2 价值 1

如何创建一个 PHP 数组生成器来做到这一点?

标签: php

解决方案


回答您的具体问题... 下面的脚本将生成一个包含 200 个键的数组,其中随机包含 20% 的值 1 和 80% 的值 2

$val_1p = $Array_Generator['Values']['Value_1']['Percent']; //Get percentage of value 1
$value_1 = $Array_Generator['Values']['Value_1']['Value']; //Get actual value of value 1

$val_2p = $Array_Generator['Values']['Value_2']['Percent']; //Get percentage of value 2
$value_2 = $Array_Generator['Values']['Value_2']['Value']; //Get actual value of value 2

$max = $Array_Generator['Max_Values'];  //Get max

$maxa = $val_1p/100 * $max;  //Get total number of value 1s to generate based on the percentage of they existence within the 200 =40
$maxb = $val_2p/100 * $max;  //Get total number of value 1s to generate based on the percentage of they existence within the 200 =40

$ff_1 = array_fill(0,$maxa,$value_1); //Make array with 20% of value 1
$ff_2 = array_fill(0,$maxb,$value_2); //Make array with 80% of value 2

$ff = array_merge($ff_1,$ff_2); //Combine the seperate arrays

shuffle($ff); //Shuffle them
print_r($ff);

推荐阅读