如何在php中总结具有相同键的单维数组的值

例如:如果 strArr 是 ["B:-1", "A:1", "B:3", "A:5"] 那么你的程序应该返回字符串 A:6,B:2。

您的最终输出字符串应按字母顺序返回键。排除求和后值为 0 的键。示例 输入:array("X:-1", "Y:1", "X:-4", "B:3", "X:5") 输出:B:3,Y:1


幕布斯7119047
浏览 131回答 1
1回答

UYOU

简单的家庭作业。您必须将explode每一对放入一个数组中,并对每个字母的值求和。然后排序(ksort按键),检查并跳过生成的数组中是否有 0:<?php&nbsp; &nbsp; $sums = array();&nbsp; &nbsp; $arr = array("X:-1", "Y:1", "X:-4", "B:3", "X:5");&nbsp; &nbsp; foreach ($arr as $key => $pair) {&nbsp; &nbsp; &nbsp; &nbsp; $pairArray = explode(":", $pair);&nbsp; &nbsp; &nbsp; &nbsp; (!array_key_exists($pairArray[0], $sums))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ? $sums[$pairArray[0]] = (int)$pairArray[1]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; : $sums[$pairArray[0]] += (int)$pairArray[1];&nbsp; &nbsp; }&nbsp; &nbsp; print_r($sums);&nbsp; &nbsp; ksort($sums);&nbsp; &nbsp; $result = array();&nbsp; &nbsp; foreach ($sums as $key => $value) {&nbsp; &nbsp; &nbsp; &nbsp; if ($value != 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; array_push($result, $key . ":" . $value);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; $result = implode(",", $result);&nbsp; &nbsp; echo $result;?>输出:Array(&nbsp; &nbsp; [X] => 0&nbsp; &nbsp; [Y] => 1&nbsp; &nbsp; [B] => 3)B:3,Y:1
打开App,查看更多内容
随时随地看视频慕课网APP