【问题标题】:How to get a non-random value from a randomly selected value?如何从随机选择的值中获​​取非随机值?
【发布时间】:2015-10-12 22:50:12
【问题描述】:

我正在尝试为随机选择的值选择一个非随机值。

  • 第一列代表销售编号(1-30)
  • 第二列显示必须随机选择的项目
  • 第三列显示该商品的相应价格

鉴于该项目是随机选择的,我该如何实现?

我曾想过使用 switch 语句,但这可能会变得混乱。

$items = array( ‘clock’ , ‘kettle’ , ‘mug’ , ‘toaster’ , ‘CD’);
$prices = array( '£30', '£19', '£5' , '£14' , '£7');

for($i = 0; $i < 30; $i++) {
    $sales[$i][0] = $i + 1; //Starts at 1 and increments
    $sales[$i][1] =  $items[rand(0,4)]; //Item chosen at random
    $sales[$i][2] = //Should be the corresponding price for the above item.
}

【问题讨论】:

  • $random = rand(0,4); $sales[$o][1] = $items[$random]; $sales[$i][2] = $items[$random]; ?!
  • 显示您的 $sales 数组或存储您的定价信息的任何位置。否则,我们不知道如何为您提供帮助。目前尚不清楚您如何将$items 中的项目与任何销售定价相关联。
  • .. 或array_rand()
  • @MikeBrant 道歉,已编辑。会放 '$random = rand(0,4);'在循环内然后使用 $items[$random]; $价格[$随机];工作吗?
  • 为什么不将商品和价格存储在一个单一的多维数组中? $data = array (array('item' =&gt; 'clock', 'price' =&gt; 30), array('item' =&gt; 'kettle', 'price' =&gt; 19), ...)?

标签: php arrays random variable-assignment


【解决方案1】:
$items = array( ‘clock’ , ‘kettle’ , ‘mug’ , ‘toaster’ , ‘CD’);
$prices = array( '£30', '£19', '£5' , '£14' , '£7');

for($i = 0; $i < 30; $i++) {
    $sales[$i][0] = $i + 1; //Starts at 1 and increments
    $sales[$i][1] =  $items[rand(0,4)]; //Item chosen at random
    $sales[$i][2] = //Should be the corresponding price for the above item
}

观看和学习:

$items = array( ‘clock’ , ‘kettle’ , ‘mug’ , ‘toaster’ , ‘CD’);
$prices = array( '£30', '£19', '£5' , '£14' , '£7');

for($i = 0; $i < 30; $i++) {
    $random = rand(0,4);

    $sales[$i][0] = $i + 1; //Starts at 1 and increments
    $sales[$i][1] = $items[$random]; //Item chosen at random
    $sales[$i][2] = $prices[$random];
}

【讨论】:

    猜你喜欢
    • 2019-07-30
    • 2018-07-07
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    相关资源
    最近更新 更多