通过另一个变量的值将变量值减小到零

时间:2018-04-14 01:40:36

标签: php

我知道它可能会被拒绝,但我真的需要帮助,我不能再思考了,我有4个变量,我需要通过其他3个的值减少其中一个,直到它变为零。

这是我的代码:

CustomSocketFactory MySocketFactory = new CustomSocketFactory();

OkHttpClient client = new OkHttpClient.Builder()
        .socketFactory(MySocketFactory)
        .readTimeout(largenumber, TimeUnit.SECONDS)
        .writeTimeout(largenumber, TimeUnit.SECONDS)
        .connectTimeout(largenumber, TimeUnit.SECONDS)

        .build();

RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("nombre_file", file_pais.getName())
        .addFormDataPart("nombre_pais", pais.getName())
        .addFormDataPart("file", file_pais.getName(),
                RequestBody.create(MediaType.parse("application/octet-stream"),
                        new File(filepath)
        .build();

Request request = new Request.Builder()
        .url(server_url)
        .post(requestBody)
        .build();

Call call = client.newCall(request);

Response response = call.execute();
response.body().close();

结果:

<?php
$total=10;
$var1=3;
$var2=4;
$var3=7;

echo "total: ".$total."<br>";
echo "var1: ".$var1."<br>";
echo "var2: ".$var2."<br>";
echo "var3: ".$var3."<hr>";

while($total>$var1){
    if($total>=$var1){
        $total= $total-$var1;
        echo "total: ".$total."<br>";
    }
}
?>

当然,这不是我要找的结果,但我需要:

total: 10
var1: 3
var2: 4
var3: 7

total: 7
total: 4
total: 1

我坚持到这里,如果你愿意,我需要思考。

如果其中一个变量超过Total?

感谢

修改

我知道解决方案是:

total: 10
var1: 3
var2: 4
var3: 7

total: 7
var1: 0
var2: 4
var3: 7

total: 3
var1: 0
var2: 0
var3: 6

total: 0
var1: 0
var2: 0
var3: 3

但是,如果我有30个变量怎么办?!!!我需要一个简单的解决方案

2 个答案:

答案 0 :(得分:0)

将它们放入数组中:

$total = 10
$var = array (3,4,7);
foreach ($var as &$value)   //  Reference so setting $value changes array
{
    if  $total >= $value)
    {
        $total -= $value;
        $value = 0;
    }
    else
    {
        $value -= $total;
        $total = 0;
        break;     //  Stop processing now
    }
}

答案 1 :(得分:0)

编辑:重新阅读你的问题并决定我误解了你的想法。这应该适用于您的数字或任何数字,无论总数是否可以归零。

<?php
$var = [3, 4, 5, 5, 6, 7, 8];
$total = 40;
$result = [];
for ($i = 0; $i < count($var); $i++ ) {
    $varn = "var" . ($i+1);
    if ($total > $var[$i]) {
        $result[$varn] = 0;
        $total -= $var[$i];
    } else {
        $result[$varn] = $var[$i] - $total;
        $total = 0;
    }
}
$result = ["total"=>$total] + $result;
var_export($result);
?>

这会产生输出:

array (
  'total' => 0,
  'var1' => 0,
  'var2' => 0,
  'var3' => 4,
)

以下是使用的示例:

$var = [3, 4, 5, 5, 6, 7, 8];
$total = 20;

产生:

array (
  'total' => 0,
  'var1' => 0,
  'var2' => 0,
  'var3' => 0,
  'var4' => 0,
  'var5' => 3,
  'var6' => 7,
  'var7' => 8,
)

$var = [3, 4, 5, 5, 6, 7, 8];
$total = 40;

产量:

array (
  'total' => 2,
  'var1' => 0,
  'var2' => 0,
  'var3' => 0,
  'var4' => 0,
  'var5' => 0,
  'var6' => 0,
  'var7' => 0,
)