drl6054 2019-06-11 08:52 采纳率: 0%
浏览 78
已采纳

对已排序的关联数组进行迭代

I have array with positive int values like [4, 1, 75, 52, 5, 24]. I need to find two values with minimal difference. Also, I need the original keys of those two. So, I sorted the array with asort() to keep the keys. Now when I iterate I have a problem - I can't use $key + 1 to point to next element and using next() and prev() makes it difficult to get the keys (once you use next or prev pointer is moved):

for ($i = 0; $i < count($sorted)-1; $i++) {
  if (current($sorted) - next($sorted) < $min) {
    //echo prev($sorted) - next($sorted) . '<br>'; 
  }
}

What would you do?
(Feel free to alter array in any other form if that makes this easier - asort is not necessary)

If I need to explain one more time: I have a problem with keys. Finding the closest values is not a problem.

  • 写回答

2条回答 默认 最新

  • dongzhenyin2001 2019-06-11 09:24
    关注

    I completely revamped your snippet. You can take whatever you want from below snippet,

    $array = [4, 1, 5, 52, 75, 52, 24];
    function difference($arr)
    {
        $n = count($arr);
    // Initialize difference
        // as infinite
        $diff = PHP_INT_MAX;
    // Find the min diff by comparing
        // difference of all possible
        // pairs in given array
        $two_values = [];
        for ($i = 0; $i < $n - 1; $i++) {
            for ($j = $i + 1; $j < $n; $j++) {
                if (abs($arr[$i] - $arr[$j]) < $diff) {
                    $diff = abs($arr[$i] - $arr[$j]);
                    $two_values['values'] = [$arr[$i], $arr[$j]];
                    $two_values['keys']   = [$i, $j];
                    $two_values['diff']   = $diff;
                }
            }
        }
    
    // Return min diff
        return $two_values;
    }
    print_r(difference($array));
    

    Demo.

    Please let me know if something is not getting.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗