sum numbers in a replaced string by numbers

2019-03-03 17:34发布

问题:

lets say i have those two arrays

   $letters = array('a','b','c', 'd', 'e');
   $replace = array( 1,  5,  10, 15 , 20);
   $text = "abd cde dee ae d" ;
   $re = str_replace($letters, $replace, $text) ;
   echo $re ;  //this output:

     1515 101520 152020 120 15 

Now i want sum the above numbers for each word and the result should be like that:

     21 45 55 21 15

what i tried is :

    $resultArray = explode(" ", $re); 

    echo array_sum($resultArray).'<br />' ; // but it output wrong result. 
                                           // it output this : 255190

how can i achieve this ?

any help much apreciated.

EDIT:

with arabic letters like that

   $letters = array('ا', 'ب','ج','د' ) ;
   $replace = array(1, 5, 10, 15 ) ;
   $text = "جا باب جب"; 

回答1:

Convert the string into an array and use array_sum.

array_sum(explode(' ', $re));

Edit

Sorry, misunderstood:

$letters = array('a','b','c', 'd', 'e');

$replace = array( 1,  5,  10, 15 , 20);

$text = "abd cde dee ae d" ;

$new_array = explode(' ', $text);

$sum_array = array();

foreach ($new_array as $string)
{

  $nums = str_split($string);

  foreach ($nums as &$num)
  {
    $num = str_replace($letters, $replace, $num);
  }

  $sum_array[] = array_sum($nums);

}

echo implode(' ', $sum_array);


回答2:

Instead of replacing the letters with numbers I would suggest just looking up the letters in the replace array one at a time:

EDIT

<?php
    $text = "abd cde dee ae d";
    $replace = array('a' => 1, 'b' => 5, 'c' => 10, 'd' => 15, 'e' => 20);
    $letters = str_split($text);
    $sums = array(0);

    foreach ($letters as $letter) {
        // Add a new element to the sum array.
        if ($letter == ' ') {
            $sums[] = 0;
        } else {
            $sums[count($sums) - 1] += $replace[$letter];
        }
    }

    echo implode(" ", $sums);
?>

Here is a working example: http://codepad.org/Cw71zuKD



标签: php arrays sum