如果键是相同的,则遍历数组元素和减去值

时间:2017-09-18 06:35:05

标签: php arrays

我循环遍历两个名为$ result_start和$ result_end arrays的数组。

这里有2个案例:

1)如果数组具有相同的键 - >减去值(这里没问题)

让我们说:

$result_start[18]['fld_IndActive1Imp'] = 100;
$result_start[5]['fld_IndActive1Imp'] = 100;

$result_end[18]['fld_IndActive1Imp'] = 250;
$result_end[5]['fld_IndActive1Imp'] = 300;

所以价值应该是

$consumptions[0] => 150  // result_end - result_start (for key #18)
$consumptions[1] => 200 // result_end - result_start (for key #5)

在这种情况下,我写的代码在下面并且工作正常:

if (!array_diff_key($result_start, $result_end) && !array_diff_key($result_end, $result_start)) {
        for ($index = 0; $index < count($result_start); $index++) {
            $consumptions[$index]['active1_imp'] = $result_end[$index]['fld_IndActive1Imp'] - $result_start[$index]['fld_IndActive1Imp'];
        }
}

2)如果1个阵列有更多的键,那么另一个(有问题)

例如,假设数组的值如下所示:

$result_start[18]['fld_IndActive1Imp'] = 100;
$result_start[5]['fld_IndActive1Imp'] = 100;

$result_end[5]['fld_IndActive1Imp'] = 300;

在这种情况下,消费应该是,

$consumptions[0] => 0 // // No end value for key #18 so it's 0
$consumptions[1] => 200 // result_end - result_start (for key #5)

我在编写第二个案例时遇到了问题。有什么提示吗?

2 个答案:

答案 0 :(得分:0)

你必须检查第二个数组中的索引是否设置

试试这个

$consumptions[$index]['active1_imp'] = (isset($result_end[$index]['fld_IndActive1Imp']) ? $result_end[$index]['fld_IndActive1Imp'] - $result_start[$index]['fld_IndActive1Imp'] : 0;

答案 1 :(得分:0)

我解决了这个问题:

if (count($result_start) > count($result_end)) { // start > end
    $index = 0;
    foreach ($result_start as $start) {
        if (!array_key_exists($start['fld_DeviceId'], $result_end)) { // yoksa 
            $consumptions[$index]['active1_imp'] = 0;
        } else {
            $consumptions[$index]['active1_imp'] = $result_end[$start['fld_DeviceId']]['fld_IndActive1Imp'] - $start['fld_IndActive1Imp'];
        }
        $index++;
    }
} else { // end > start
    $index = 0;
    foreach ($result_end as $end) {
        if (!array_key_exists($end['fld_DeviceId'], $result_start)) { // yoksa
            $consumptions[$index]['active1_imp'] = 0;
        } else {
            $consumptions[$index]['active1_imp'] = $end['fld_IndActive1Imp'] - $result_start[$end['fld_DeviceId']]['fld_IndActive1Imp'];
        }
        $index++;
    }
}