【问题标题】:How to compare previous key of an associative array with current key in PHP?如何将关联数组的前一个键与 PHP 中的当前键进行比较?
【发布时间】:2019-03-27 15:54:07
【问题描述】:

我想从数组中回显最常见的数字。我有一个数组,我想将前一个键与我的数组的当前键进行比较。我该怎么做?

我做了两个 foreach 循环:

$mostCommon = 0;
foreach ($_SESSION['array'] as $key => $value) {
       foreach ($_SESSION['array'] as $key2 => $value2){
           $key++;
       }
       if(current key is higher than previous key){
           $mostCommon = $value;
       }
}

这就是我不想这样做的方式。

【问题讨论】:

  • 我没有看到 common number 和比较键之间的联系。

标签: php foreach compare key


【解决方案1】:

您可以将前一个键保存在循环之外。

示例:

$previousKey = null;
foreach ($array as $key => $value) {
    if ($key > $previousKey){ //If current key is greater than last key

    }
    $previousKey = $key;
}

$highestKey 将被设置为该数组中最大的键。

【讨论】:

    【解决方案2】:

    可以使用 array_count_values 找到最常见的数字。
    array_count_values 的输出是一个关联数组,其中键是值,值是它在数组中的次数。
    使用 asort 对数组进行排序以保留键。
    翻转数组以获取最常见的值并回显最后一项。

    $arr = [1,2,2,3,3,3,3,1,2,5,3,7];
    
    $counts = array_count_values($arr);
    asort($counts);
    $flipped = array_flip($counts);
    echo "most common number: " . end($flipped) . " is in the array " . end($counts) . " times";
    //most common number: 3 is in the array 5 times
    

    https://3v4l.org/qSD4J

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-27
      • 1970-01-01
      • 1970-01-01
      • 2012-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多