简体   繁体   English

内部循环运行的PHP函数不起作用(带代码)

[英]PHP function running inside loop not working (with code)

I am running this function 我正在运行此功能

function Age($month, $day, $year) {
    date_default_timezone_set('America/New_York');
    $dob = $month .''. $day .''. $year;
    $startDate = strtotime($dob);
    $endDate = time();
    $dif = $endDate - $startDate;

    return $years = (date('Y', $dif) - 1970) .' y, '. ($months = date('n', $dif) - 1).' m';
}

inside a foreach loop (some CodeIgniter markup): foreach循环内部(一些CodeIgniter标记):

foreach ($users as $row) {
    echo $this->includes->Age($row->birth_month, $row->birth_day, $row->birth_year)
  }

The loop works OK, showing all my users. 循环工作正常,显示我的所有用户。

But the problem is that it calculates the age correctly for the first user and then shows that same age for all other users. 但问题是它会为第一个用户正确计算年龄,然后为所有其他用户显示相同的年龄。 I should point out that all other user's data is correct, only the age is wrong. 我应该指出所有其他用户的数据都是正确的,只有年龄是错误的。

Anyone know how to fix this? 有人知道怎么修这个东西吗?

Thanks! 谢谢!

Your $dob looks malformed. 你的$dob看起来很糟糕。 Try $dob = $year . '-' . $month . '-' $day; 尝试$dob = $year . '-' . $month . '-' $day; $dob = $year . '-' . $month . '-' $day;

You're missing space/separators. 你错过了空格/分隔符。

$dob = $month .''. $day .''. $year;

should be 应该

$dob = $month .'/'. $day .'/'. $year;

edit: Ambiguity. 编辑:歧义。 If using mm-dd-yyyy format, should be / 如果使用mm-dd-yyyy格式,应该是/

. and - indicate dd-mm-yyyy - - 表示dd-mm-yyyy

Maybe CI is caching the result? 也许CI正在缓存结果?
Seems that function Age is correct 似乎功能年龄是正确的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM