【问题标题】:PHP - get min and max values of numbers with special difference to each otherPHP - 获取彼此具有特殊差异的数字的最小值和最大值
【发布时间】:2017-03-20 08:42:00
【问题描述】:

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

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

我这排数字的特殊差是 1800。当一个数字与下一个数字正好相差 1800 时,它们是同一行的数字。如果不是,它们是另一行的数字。所以我需要一个函数,它会为上面提到的数组产生以下输出:

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

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

【问题讨论】:

  • 向我们展示您的尝试,我们将帮助您编写代码,而不是整个代码
  • 这是一个非常简单的逻辑,所以请向我们展示您到目前为止所做的工作,以便我们为您指明正确的方向
  • 对不起,我只是在纸上勾勒出一个合乎逻辑的解决方案。 PHP 中还没有任何代码。

标签: php arrays numbers


【解决方案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

【讨论】:

  • 哇,真快。正是,我需要的!谢谢。
【解决方案2】:

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

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;
}

【讨论】:

    猜你喜欢
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 2012-10-09
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多