PHP - 获取彼此具有特殊差异的数字的最小值和最大值

时间:2017-03-20 08:42:00

标签: php arrays numbers

我在从一行数字中获取最小值和最大值时遇到问题,其中特殊差异为1800。为了更好地理解,我想给你以下例子:

array(0,1800,3600,5400,7200,12600,14400,16200,23400,25200);

我的数字行的特殊差异是1800.当一个数字与下一个数字完全相差1800时,它们是同一行的数字。如果没有,它们是另一行的数字。所以我需要一个函数,它将为上面提到的数组产生以下输出:

  • 输出1:最小值0,最大值7200
  • 输出2:最小值12600,最大值16200
  • 输出3:最小值23400,最大值25200

我希望你理解我的问题。对不起我的英语,并提前致谢。

2 个答案:

答案 0 :(得分:1)

总是更好地展示你目前为止尝试过的一些代码。 但是这里是一个非常简短的代码示例。

$lists       = [];
$special     = 1800;
$array       = [0, 1800, 3600, 5400, 7200, 12600, 14400, 16200, 23400, 25200];
$currentList = [];
foreach ($array as $number) {
    if (empty($currentList)) {
        $currentList[] = $number;
    } else {
        $last =(end($currentList) + $special);
        if ($number === $last) {
            $currentList[] = $number;
        } else {
            $lists[]     = $currentList;
            $currentList = [$number];
        }
    }
}
$lists[] = $currentList;
var_dump($lists);

这将输出以下数组,该数组可以在您想要的输出中进行转换。

array (size=3)   0 => 
    array (size=5)
      0 => int 0
      1 => int 1800
      2 => int 3600
      3 => int 5400
      4 => int 7200   1 => 
    array (size=3)
      0 => int 12600
      1 => int 14400
      2 => int 16200   2 => 
    array (size=2)
      0 => int 23400
      1 => int 25200

答案 1 :(得分:0)

您可以创建一个辅助函数来迭代输入并将值添加到行数组

function getRows($input, $specialDifference) {
    $rows = array();
    $newRow = true;
    for ($index = 0; $index < count($input); $index++) {
        if ($newRow) {
            $rows[] = array();
            $newRow = false;
        }
        $rows[count($rows) - 1][]= $input[$index];
        $newRow = ((count($input) > $index + 1) && ($input[$index + 1] - $input[$index] !== $specialDifference));
    }
    return $rows;
}