我想对一个数字中的所有数字求和

i want to sum all digit in a number

我想将数字中的所有数字相加,如果它是 11,22,那么我只想显示 11 或 22,否则我想让它成为一个数字。 例子 30=3+0=3 28=2+8=10=1+0=1

我刚刚做了一个代码但是有错误 请帮忙

<?php
$day = 17;  
$month = 8;   
$year = 1993;    

function sumday($day)   
{   
     if ($day == 11)    
    {   
        $sday = 11;   
    }    
    elseif ($day == 22)     
    {    
        $sday = 22;   
    }   
    elseif ($day == 29)    
    {   
        $sday = 11;   
    }    
    else    
        {   
             do {    
            $nday = $day . "";    
            $sday = 0;    
            for ($i = 0; $i < strlen($nday); ++$i)   
            {    
                $sday += $nday[$i];    
            }    
            while ($sday <=9);    

} 

return $sday;
}   

试试这个:

else {   
     $nday = $day . "";   //moved out wrom loop
     do {   
        $sday = 0;
        for ($i = 0; $i < strlen($nday); ++$i)   
        {    
            $sday += $nday[$i];    
        } 
        $nday = $sday . ""; // you forget this line   
        while ($sday <=9);    

} 

首先,我建议您学习将函数执行的任务分开。

你要求求和一个数字的数字,你可以先创建一个函数叫做sum_digits

<?php

function sum_digits($num) {
    if ($num < 10) 
        return $num;
    return $num % 10 + sum_digits(floor($num/10));
}

然后通过条件做任何你需要做的事情。

please refer to unnikked's answer,这是一个很好的答案。 这是完整的代码,结合了 unnikked 的回答

<?php
$day = 17;  
$month = 8;   
$year = 1993;    

function sumday($day)   
{   
     if ($day == 11)    
    {   
        $sday = 11;   
    }    
    elseif ($day == 22)     
    {    
        $sday = 22;   
    }   
    elseif ($day == 29)    
    {   
        $sday = 11;   
    }    
    else{  
        $sday = $day;
        do {    
             $sday = $sday % 10 + floor($sday/10);
        } while ($sday >= 10); 
    }
return $sday;
}

?>

编辑: 如果您想 return while 循环中的总和为 11,22,33,则将条件放在 while 循环中而不是使用 if else 条件,它要简单得多:)

function sumday($day)   
{   
    $sday = $day;
    while ($sday >= 10 && $sday != 11 && $sday != 22 && $sday != 29){
        $sday = $sday % 10 + floor($sday/10);
    }
return $sday;
}

编辑: 这是可以拆分一天并对它们求和的逻辑

function sumday($day)   
{   
    $sday = $day;
    $arrday = str_split($sday); // split the day into array
    $sumarrday = 0;
    for($i = 0; $i < strlen((string)$sday); $i++){
        $sumarrday = $sumarrday + $arrday[$i]; // sum the day from the array
    }
    $sday = $sumarrday; 
    // here you can modify the condition of while statement for your needs
    // for example, if you want to return 29 when 29 shows up, add this to your condition, && $sday != 29
    while ($sday >= 10){
        $sday = $sday % 10 + floor($sday/10);
    }   
    return $sday;
}