从数组中删除第一个元素,并从数组中的所有后续值中减去该值

问题描述 投票:0回答:2

我有这个功能:

function pairwiseDifference($arry) 
{
    $n = count($arry) - 1;  // you can add the -1 here
    $diff = 0;
    $result = array();

    for ($i = 0; $i < $n; $i++) 
   { 
       // absolute difference between 
       // consecutive numbers 
       $diff = abs($arry[$i] - $arry[$i + 1]); 
       echo $diff." ";
       array_push($result, $diff);   // use array_push() to add new items to an array
   }

   return $result;  // return the result array
}

$arry = array(20,10,10,50);
echo "<br> Percent of commisions are: ";

// this echos 10,0,40 and assigns whatever your function returns 
// to the variable $diffArray
$diffArray = pairwiseDifference($arry);

问题是我不期待这个输出
因为数组的第一个数字(20)是我的佣金
其他数字是我父母的佣金(10,10,50)。 所以基本上我需要这样输出:(0,0,30)
因为我拿了20的佣金,
第一个家长不会拿走任何东西,因为我的佣金较少 (10)
第二位家长不会拿走任何东西,因为我的佣金较少 (10)
只有最后一位家长拿了 30,因为大于我的佣金(50 - 20 我的佣金)。
预先感谢

php arrays subtraction
2个回答
1
投票

由于数组的第一个元素是您的佣金,其他元素是父母的佣金,并且由于您似乎不想将您的佣金包含在结果数组中,因此您可以执行以下操作:

function pairwiseDifference($arry) 
{
    $n = count($arry);
    $diff = 0;
    $result = array();

    $myComm = $arry[0];  // your commision

    for ($i = 1; $i < $n; $i++) 
    {
        $diff = 0;                     // set $diff to 0 as default
        if($myComm < $arry[$i])          // if your commision < parent commision
            $diff = $arry[$i] - $myComm;
        echo $diff." ";
        array_push($result, $diff);
    }

    return $result;
}

$arry = array(20,10,10,50);
echo "<br> Percent of commisions are: ";

$diffArray = pairwiseDifference($arry);

echo $diffArray[0];  // prints 0
echo $diffArray[1];  // prints 0
echo $diffArray[2];  // prinst 30

1
投票

要根据您的代码调整逻辑,只需进行 3 处修改。

  • 创建一个
    $max
    变量并为其分配
    $arry[0]
    的值。
  • 如果当前最大值大于当前最大值,则将差值设为
    0
    ,否则取差值。
  • 使用
    max()
    函数再次计算新的最大值。

片段:

<?php

function pairwiseDifference($arry) 
{
    $n = count($arry) - 1;  // you can add the -1 here
    $diff = 0;
    $result = array();
    $max = $arry[0]; // new addition
    for ($i = 1; $i <= $n; $i++)  // new modification <= n instead of < n
   { 
       // absolute difference between 
       // consecutive numbers 
       $diff = $max < $arry[$i] ? $arry[$i] - $max : 0; // new modification
       $max = max($max, $arry[$i]); // new modification
       echo $diff." ";
       array_push($result, $diff);   // use array_push() to add new items to an array
   }

   return $result;  // return the result array
}

$arry = array(20,10,10,50);
echo "<br> Percent of commisions are: ";

// this echos 10,0,40 and assigns whatever your function returns 
// to the variable $diffArray
$diffArray = pairwiseDifference($arry);
© www.soinside.com 2019 - 2024. All rights reserved.