【问题标题】:How to store multiple value in for-loop? php如何在for循环中存储多个值? php
【发布时间】:2021-05-06 04:16:44
【问题描述】:

系统详情:客户可以购买一个号码(从0000到9999)的价格,系统会记录客户每次购买的号码。在一天结束时,系统应返回累积价格最高和最低的数字。

例如, 亚历克斯以 50 美元的价格购买编号 1234, Jasmine 以 100 美元的价格购买编号 5555, 约翰以 100 美元的价格购买 1234 号, 现在,系统应该显示数字 1234 的价格是 150 美元,数字 5555 的价格是 100 美元。

我这样做的想法是创建一个数组 [10000] 来保存 10000 个数字,每个数字都有自己的变量调用 '$price'。

但我的问题是数组如何同时保存变量“数字”和“价格”?

$numbers = array(10000);
$price = $price;

//when user insert a number
    for(i=0000;i<=9999;i++){
        number=array[i];
        
//user can insert a price for every number inserted
        while(number>0){
            <input value="" name="price">
        }
//the for loop will return every number and its profit when ended.
    return $number , $price;
    }   

这是正确的做法吗?

【问题讨论】:

  • number=array[i]; 必须是 $number[] = array[i];

标签: php for-loop


【解决方案1】:

创建初始数组很容易:

$numbers = [];

键是数字,值是为该数字支付的总价格(假设您不需要存储每个人支付的价格,而只需存储为每个数字支付的“总”价格):

// When a person buys number $n for $price:
$numbers[ $n ] += $price;

显示为每个号码支付的总价格:

foreach ( $numbers as $n => $price ) {
  echo "Number $n cost a total of $price\n";
}

要确定最便宜和最贵的数字(及其价格),请按价格(即价值)对数组进行排序:

asort( $numbers, SORT_NUMERIC );

那么,最便宜的号码是第一个:

$cheapest_number = array_key_first( $numbers );
$cheapest_price = $numbers[ $cheapest_number ];

最贵的是最后一个:

$most_expensive_number = array_key_last( $numbers );
$most_espensive_price = $numbers[ $most_expensive_number ];

【讨论】:

    猜你喜欢
    • 2013-12-07
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 2021-11-18
    • 2021-11-09
    • 2018-04-12
    相关资源
    最近更新 更多