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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?