当前位置: 动力学知识库 > 问答 > 编程问答 >

How to extract adjacent pair of words in associative array in 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?

网友答案:
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;
    }

网友答案:

Store keys on a temporary array where keys are integers on which you can easily get the next key, and use it to parse your main array.

$tmp_array = array();
foreach ($weight as $key => $val) {
    $tmp_array[] = $key;
}
$array_length = count($tmp_array);
for ($i = 0; i < array_length - 2; ++$i) {
    echo $weight[$tmp_array[$i+1]], '-', $weight[$tmp_array[$i]], ' = ', ($weight[$tmp_array[$i+1]] - $weight[$tmp_array[$i]], PHP_EOL;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: