$aa =Array(
[R,99] => B [I,100] => A [A,101] => D [S,102] => C [E,103] => D [C,104] => B [R,105] => A );
$cc = array( "A" =>"1", "B" => "2", "C" => "3", "D" => "4", "E" => "5", "F" => "6", "G" => "7", );
需求:::将aa数组里面的 r=b,然后匹配cc数组里面的值,b对应的值为2,如果aa里面有两个r那么将他们的值相加
$str =""; foreach ($aa as $key => $v) { $kk = substr($key,0,1); $str .= substr($key,0,1)."=".$cc[$v].","; }
得到 str=' R=2,I=1,A=4,S=3,E=4,C=2,R=1';
然后将str这个字符串处理成
Array ( [R] => 3 [I] => 1 [A] => 4 [S] => 3 [E] => 4 [C] => 2 )
这种格式,:注意,这里拼接数组的时候,键名如果相同会被替换,需求是,如果键名相同,则键值相加
思路:
先将str以逗号打散成数组
Array ( [0] => R=2 [1] => I=1 [2] => A=4 [3] => S=3 [4] => E=4 [5] => C=2 [6] => R=1 )
循环这个数组,然后再循环里再将新数组的值,再次以=打散成新数组,
Array ( [0] => R [1] => 2 )
Array ( [0] => I [1] => 1 )
Array ( [0] => A [1] => 4 )
Array ( [0] => S [1] => 3 )
Array ( [0] => E [1] => 4 )
Array ( [0] => C [1] => 2 )
Array ( [0] => R [1] => 1 )
然后将新数组的0下标的值作为键名组成新数组,如果键名相同,键值相加,否则不用
代码:
$str = rtrim($str,","); $arr1 = explode(',',$str); $arr2 =[]; foreach ($arr1 as $k => $va) { $arr3 = explode('=',$va); aaa($arr3); if(isset($arr2[$arr3[0]])) { $arr2[$arr3[0]] += $arr3[1]; }else{ $arr2[$arr3[0]] = $arr3[1]; } }
function aaa($ccd){
echo "<pre>";
print_R($ccd);
echo "</pre>";
}
优化思路:不用再拼接字符串,直接判断相加
$aa = Array ( [R,99] => B [I,100] => A [A,101] => D [S,102] => C [E,103] => D [C,104] => B [R,105] => A );
$cc = Array ( [A] => 1 [B] => 2 [C] => 3 [D] => 4 [E] => 5 [F] => 6 [G] => 7 );
$arr5 = []; foreach ($aa as $key => $v) { $kk = substr($key,0,1); if(isset($arr5[$kk])){//如果键名存在,吧值相加 $arr5[$kk] += $cc[$v]; }else{ $arr5[$kk] = $cc[$v]; } }