1 回答

TA貢獻(xiàn)1878條經(jīng)驗(yàn) 獲得超4個(gè)贊
簡(jiǎn)單的家庭作業(yè)。您必須將explode每一對(duì)放入一個(gè)數(shù)組中,并對(duì)每個(gè)字母的值求和。然后排序(ksort按鍵),檢查并跳過(guò)生成的數(shù)組中是否有 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 關(guān)注
- 157 瀏覽
添加回答
舉報(bào)