1 回答
TA贡献1878条经验 获得超4个赞
简单的家庭作业。您必须将explode每一对放入一个数组中,并对每个字母的值求和。然后排序(ksort按键),检查并跳过生成的数组中是否有 0:
<?php
$sums = array();
$arr = array("X:-1", "Y:1", "X:-4", "B:3", "X:5");
foreach ($arr as $key => $pair) {
$pairArray = explode(":", $pair);
(!array_key_exists($pairArray[0], $sums))
? $sums[$pairArray[0]] = (int)$pairArray[1]
: $sums[$pairArray[0]] += (int)$pairArray[1];
}
print_r($sums);
ksort($sums);
$result = array();
foreach ($sums as $key => $value) {
if ($value != 0) {
array_push($result, $key . ":" . $value);
}
}
$result = implode(",", $result);
echo $result;
?>
输出:
Array
(
[X] => 0
[Y] => 1
[B] => 3
)
B:3,Y:1
- 1 回答
- 0 关注
- 128 浏览
添加回答
举报