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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog