如何在数组映射函数中使用碳计算年龄?
How to calculate age using carbon in array map function?
此应用程序内置于 Lavavel 5。我有一个 table 的出生年份值。我使用此查询查询 table:
$tarikh = DB::table('itemregistrations')
->select('itemregistrations.lahir_dd', 'itemregistrations.lahir_mm', 'itemregistrations.lahir_yy')
->get();
dd($tarikh);产生这个输出:
Collection {#709 ▼
#items: array:1123 [▼
0 => {#681 ▼
+"lahir_dd": 9
+"lahir_mm": "June"
+"lahir_yy": 1979
}
1 => {#670 ▶}
2 => {#680 ▶}
3 => {#713 ▶}
我想使用 carbon 计算年龄并使用数组映射插入集合(我之前的代码):
$tarikh->map(function ($detail) {$detail->Umur = "{$detail->lahir_yy}->diffInYears(\Carbon::now())";
return $detail;
});
更改为 Ijas 建议代码:
$tarikh->map(function ($detail) {
$detail->Umur = \Carbon\Carbon::parse($detail->lahir_yy)->diffInYears();
return $detail;
});
您可以将差异计算为,
$tarikh->map(function ($detail) {
$detail->Umur = \Carbon\Carbon::parse($detail->lahir_yy)->diffInYears();
return $detail;
});
Updated : Re-generated your results and applied the given solution.
Fiddle : https://implode.io/i1GanD
对于给定的上下文,这按您的预期工作。
通过修改部分代码消除的错误:
$tarikh->map(function ($detail) {
$detail->Umur = \Carbon\Carbon::createFromFormat('Y',$detail->lahir_yy)->diffInYears();
return $detail;
});
此应用程序内置于 Lavavel 5。我有一个 table 的出生年份值。我使用此查询查询 table:
$tarikh = DB::table('itemregistrations')
->select('itemregistrations.lahir_dd', 'itemregistrations.lahir_mm', 'itemregistrations.lahir_yy')
->get();
dd($tarikh);产生这个输出:
Collection {#709 ▼
#items: array:1123 [▼
0 => {#681 ▼
+"lahir_dd": 9
+"lahir_mm": "June"
+"lahir_yy": 1979
}
1 => {#670 ▶}
2 => {#680 ▶}
3 => {#713 ▶}
我想使用 carbon 计算年龄并使用数组映射插入集合(我之前的代码):
$tarikh->map(function ($detail) {$detail->Umur = "{$detail->lahir_yy}->diffInYears(\Carbon::now())";
return $detail;
});
更改为 Ijas 建议代码:
$tarikh->map(function ($detail) {
$detail->Umur = \Carbon\Carbon::parse($detail->lahir_yy)->diffInYears();
return $detail;
});
您可以将差异计算为,
$tarikh->map(function ($detail) {
$detail->Umur = \Carbon\Carbon::parse($detail->lahir_yy)->diffInYears();
return $detail;
});
Updated : Re-generated your results and applied the given solution.
Fiddle : https://implode.io/i1GanD
对于给定的上下文,这按您的预期工作。
通过修改部分代码消除的错误:
$tarikh->map(function ($detail) {
$detail->Umur = \Carbon\Carbon::createFromFormat('Y',$detail->lahir_yy)->diffInYears();
return $detail;
});