PHP在数组键中查找匹配并对值求和

时间:2017-08-14 16:13:50

标签: php arrays

输入:

list

我需要将任何不包含短语“SSN CHECK FAILED”的键的值相加

我正在使用此功能:

Array
(
    [ADDRESS CHECK FAILED, ADDRESS DISCREPANCY] => 716
    [SSN CHECK FAILED, DOB CHECK FAILED] => 15
    [DOB CHECK FAILED] => 139
    [NO ISSUES] => 189
    [DOB CHECK FAILED, ADDRESS DISCREPANCY] => 51
    [DOB CHECK FAILED, ADDRESS CHECK FAILED, ADDRESS DISCREPANCY] => 23
    [SSN CHECK FAILED] => 3
    [ADDRESS DISCREPANCY] => 33
)

像这样:

function in_array_r($needle, $haystack, $strict = true) {
foreach ($haystack as $item) {
    if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
        return true;
    }
}

return false;
}

foreach ($issues_totals as $key => $value){ if (!in_array_r("SSN CHECK FAILED", $key)){ $total_with_no_issue += $value; } } 是上面的数组,$issues_totals是我要找的值。问题是,此代码$total_with_no_issue返回 1169 ,这是整个数组的总和。我希望它返回 1151

任何帮助表示赞赏!

3 个答案:

答案 0 :(得分:2)

您可以使用array_filter排除包含目标字符串的所有键:

$valid = array_filter($array, function ($e) {
    return strpos($e, 'SSN CHECK FAILED') === false;
}, ARRAY_FILTER_USE_KEY);

然后只需使用array_sum来获取其余内容:

$total_with_no_issue = array_sum($valid);

如您所述,这实际上会返回 1151 而非 1159 ,请参阅https://eval.in/845367

答案 1 :(得分:2)

我希望这个也会有所帮助。

解决方案1: Try this code snippet here

<?php
ini_set('display_errors', 1);
$array=Array
(
    "ADDRESS CHECK FAILED, ADDRESS DISCREPANCY" => 716,
    "SSN CHECK FAILED, DOB CHECK FAILED" => 15,
    "DOB CHECK FAILED" => 139,
    "NO ISSUES" => 189,
    "DOB CHECK FAILED, ADDRESS DISCREPANCY" => 51,
    "DOB CHECK FAILED, ADDRESS CHECK FAILED, ADDRESS DISCREPANCY" => 23,
    "SSN CHECK FAILED" => 3,
    "ADDRESS DISCREPANCY" => 33
);
$requiredKeys=  array_flip(preg_grep('/SSN CHECK FAILED/', array_keys($array),PREG_GREP_INVERT));
$result=0;
foreach($array as $key => $value)
{
    if(isset($requiredKeys[$key]))
    {
        $result+=$value;  
    }
}
echo $result;

解决方案2: Try this code snippet here

注意:这个在性能方面效率不高,但效果非常好。

<?php
ini_set('display_errors', 1);
$array=Array
(
    "ADDRESS CHECK FAILED, ADDRESS DISCREPANCY" => 716,
    "SSN CHECK FAILED, DOB CHECK FAILED" => 15,
    "DOB CHECK FAILED" => 139,
    "NO ISSUES" => 189,
    "DOB CHECK FAILED, ADDRESS DISCREPANCY" => 51,
    "DOB CHECK FAILED, ADDRESS CHECK FAILED, ADDRESS DISCREPANCY" => 23,
    "SSN CHECK FAILED" => 3,
    "ADDRESS DISCREPANCY" => 33
);

$array2=  preg_grep('/SSN CHECK FAILED/', array_keys($array),PREG_GREP_INVERT);
print_r(array_sum(array_intersect_key($array, array_flip($array2))));

答案 2 :(得分:0)

你需要做的是两件事:

1)过滤其密钥不包含您要排除的短语的项目:

$filtered = array_filter($arr, function ($item, $key) {
  return !preg_match( '#SSN CHECK FAILED#i', $key);
}, ARRAY_FILTER_USE_BOTH)

2)对过滤后的项目求和

$sum = array_reduce( $filtered, function ($a, $b){ return $a + $b; })

注意:我使用匿名函数和ARRAY_FILTER_USE_BOTH标志,认为您可以使用PHP 5.6 +