【问题标题】:Array in Controller laravel控制器 laravel 中的数组
【发布时间】:2017-08-25 03:36:06
【问题描述】:

谁能帮我修复我的代码?我有这个概念,但不知道如何将它们写入控制器中的代码

$temp=DB::table('temporary')->get();

    //dd($temp);
    if($temp['tahun'] < 'current year'){
        $temp['tahun'] = 'current year';
        $temp['nomor'] = 'nomor+1';
        $keluhan->no_laporan = $temp['nomor'];
    } else {
        $temp['nomor']++;
    }

条件: 我的临时表有 2 个属性 tahun(value=2017 int) 和 nomor (value=1 int) 我想检查我的 tahun 是否

【问题讨论】:

  • 代码中的变量$keluhan是什么?

标签: php arrays laravel laravel-5.2


【解决方案1】:

DB::table('temporary')->->get() 将返回一个集合。从您的代码来看,您似乎正在使用单列,您可以使用 first()。

对于日期可以使用简单的 date() 函数。

$temp=DB::table('temporary')->first();

//dd($temp);
if($temp->tahun < date("Y")){
    $temp->tahun = date("Y");
    $temp->nomor++;
    $keluhan->no_laporan = $temp->nomor;
} else {
    $temp->nomor++;
}

【讨论】:

    【解决方案2】:

    $temp=DB::table('temporary')-&gt;get(); 将获得一个集合。所以你必须循环。并使用Carbon 获取日期。

    foreach($temp as $temp)
    {
      if($temp->tahun < Carbon\Carbon::now()->year){
        {
          $temp->tahun=Carbon\Carbon::now()->year;
          $temp->nomor=$temp->nomor+1;
          $temp->update();
         }
       else
        {
           $temp->nomor=$temp->nomor+1;
           $temp->update();
        }
    }
    

    【讨论】:

    • 加载Carbon 只是为了获取当前年份,当您可以使用date('Y') 时似乎有些过分。
    • @fubar Carbon 是 laravel 的内置功能,更容易和语义化。对于date(),我们必须处理strtotime、格式问题、大量计算等等。和
    • Carbon 是 Laravel 中的一个依赖项,它不是内置的。要使用 date('Y') 获取当前年份,您不需要需要使用 strtotime,也不需要生成任何计算。
    • 好的。感谢您的信息。我会学习并确保它。
    • 感谢你们帮助它现在的工作,太好了。上帝保佑你。
    猜你喜欢
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 2017-02-12
    • 2019-08-06
    • 2015-11-05
    • 2017-04-19
    • 2019-02-25
    • 2019-04-26
    相关资源
    最近更新 更多