dqc42632 2017-08-14 16:13
浏览 81

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

Input:

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
)

I need to sum the value of any key that does not contain the phrase "SSN CHECK FAILED"

I am using this function:

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;
}

Like this:

foreach ($issues_totals as $key => $value){

    if (!in_array_r("SSN CHECK FAILED", $key)){

    $total_with_no_issue += $value;

  }
}

Where $issues_totals is the above array and $total_with_no_issue is the value I am looking for. The problem is that with this code $total_with_no_issue is returning 1169, which is the total of the entire array. I want it to return 1151.

Any help is appreciated!

  • 写回答

3条回答 默认 最新

  • dtol41388 2017-08-14 16:23
    关注

    You can use array_filter to exclude any keys that contain the target string:

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

    and then simply use array_sum to fetch the total of the rest:

    $total_with_no_issue = array_sum($valid);
    

    This actually returns 1151 not 1159 as you mentioned, see https://eval.in/845367

    评论

报告相同问题?

悬赏问题

  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因