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 uniapp实现如下图的图表功能
  • ¥15 u-subsection如何修改相邻两个节点样式
  • ¥30 vs2010开发 WFP(windows filtering platform)
  • ¥15 服务端控制goose报文控制块的发布问题
  • ¥15 学习指导与未来导向啊
  • ¥15 求多普勒频移瞬时表达式
  • ¥15 如果要做一个老年人平板有哪些需求
  • ¥15 k8s生产配置推荐配置及部署方案
  • ¥15 matlab提取运动物体的坐标
  • ¥15 人大金仓下载,有人知道怎么解决吗