duanji9378 2014-07-10 10:35
浏览 32
已采纳

如何在php中提取关联数组中的相邻词对?

I have an associative array in PHP like this:

$weight["a"]=1;
$weight["b"]=4;
$weight["c"]=5;
$weight["d"]=9;

Here I want to calculate pair-wise difference between consecutive array elements, e.g.,

"b-a" = 3
"c-b" = 1
"d-c" = 4

How should this be computed?

  • 写回答

2条回答 默认 最新

  • dor2p0520 2014-07-10 10:48
    关注
    Try this:
        $i = 0;
        foreach ($weight AS $curr) { 
          if ($i > 0) {
            echo '"'.array_keys($weight)[$i].'-'.array_keys($weight)[$i-1].'" = '.($curr-$prev)."<br />";    
          }
          $i++;
          $prev = $curr;
        }
    

    enter image description here

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

报告相同问题?