如何对数组中的字符串值求和

这是我的数组


Array

(

    [0] => Array

        (


            [Asan_Name_Val] => 447

            [Actual_Ratio] => 15/00/15,04/05/05

        )


    [1] => Array

        (

            [Asan_Name_Val] => 447

            [Actual_Ratio] => 10/05/11,00/06/05

        )

)

实际比率值应与其值相加,例如 15+10=15,00+05=05,15+11=26 ..... 所以我想要的所需输出采用这种格式


Array

(

    [Asan_Name_Val] => 447

    [Actual_Ratio] => 25/05/26,04/11/10

)


智慧大石
浏览 154回答 2
2回答

qq_花开花谢_0

用 PHP 写了一个 hacky 解决方案。会起作用,但强烈建议您进行优化。<?php$myArray = array(&nbsp; 0 => array(&nbsp; 'Asan_Name_Val' => '447',&nbsp; 'Actual_Ratio' => '15/00/15,04/05/05'&nbsp; ),&nbsp; 1 => array(&nbsp; 'Asan_Name_Val' => '447',&nbsp; 'Actual_Ratio' => '10/05/11,00/06/05'&nbsp; ));$sums = array_fill(0,6,'0');foreach($myArray as $arr){&nbsp; $ratio = $arr['Actual_Ratio'];&nbsp; $j=0;&nbsp; for($i=0;$i<6;$i++){&nbsp; &nbsp; $sums[$i] = sprintf("%02d", $sums[$i]+substr($ratio,$j,2));&nbsp; &nbsp; $j = $j+3;&nbsp; }}$finalRatio = "$sums[0]/$sums[1]/$sums[2],$sums[3]/$sums[4]/$sums[5]";$desiredArray['Asan_Name_Val'] = '447';$desiredArray['Actual_Ratio'] = $finalRatio;print_r($desiredArray);

牧羊人nacy

这将是一种灵活而干净的方法:<?php$input = [&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; 'Asan_Name_Val' => "447",&nbsp; &nbsp; &nbsp; &nbsp; 'Actual_Ratio' => "15/00/15,04/05/05"&nbsp; &nbsp; ],&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; 'Asan_Name_Val' => "447",&nbsp; &nbsp; &nbsp; &nbsp; 'Actual_Ratio' => "10/05/11,00/06/05"&nbsp; &nbsp; ]];$output = [];$formatter = new NumberFormatter('de_DE', NumberFormatter::DECIMAL);array_walk($input, function($entry) use (&$output, $formatter) {&nbsp; &nbsp; $values = explode("/", $entry['Actual_Ratio']);&nbsp; &nbsp; foreach($values as &$value) {&nbsp; &nbsp; &nbsp; &nbsp; $value = $formatter->parse($value);&nbsp; &nbsp; }&nbsp; &nbsp; $output[$entry['Asan_Name_Val']][] = $values;});array_walk($output, function(&$entry, $key) use ($formatter) {&nbsp; &nbsp; for ($i = 0; $i < count($entry[0]); $i++) {&nbsp; &nbsp; &nbsp; &nbsp; $sums[] = $formatter->format(array_sum(array_column($entry, $i)));&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; $entry = [&nbsp; &nbsp; &nbsp; &nbsp; 'Asan_Name_Val' => $key,&nbsp; &nbsp; &nbsp; &nbsp; 'Actual_Ratio' => implode("/", $sums)&nbsp; &nbsp; ];});print_r(array_values($output));输出显然是:Array(&nbsp; &nbsp; [0] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Asan_Name_Val] => 447&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Actual_Ratio] => 25/5/26,04/11/10&nbsp; &nbsp; &nbsp; &nbsp; ))
打开App,查看更多内容
随时随地看视频慕课网APP