【问题标题】:Implode separate date of birth values from php form从 php 表单中插入单独的出生日期值
【发布时间】:2015-07-22 16:33:20
【问题描述】:

好吧,我没有想法,我的研究已经到了终点。

有一个带有生日选择字段示例的注册表单:

<div class="row">
    <div class="col-xs-2">
        {!! Form::selectMonth('dob_month', 1, ['class'=> 'form-control']) !!}
    </div>
    <div class="col-xs-2">
        {!! Form::selectRange('dob_date', 1, 31, 1, ['class'=> 'form-control']) !!}
    </div>
    <div class="col-xs-2">
        {!! Form::selectYear('dob_year', 1930, 1997, 1991, ['class'=> 'form-control']) !!}
    </div>
</div>

当然是在 laravel 的刀片模板中。

您可以看到它的 3 个单独的选择表单,其中包含 dob_month、dob_date 和 dob_year,并且这些值现在位于用户模型中的 mutator 上

private function setDobAttribute($dob){

            $dobString = ['dob_year', 'dob_month', 'dob_date'];

            $this->attributes['dob'] = implode('-', array_values($dobString)); 

        }

dob 作为 sql 列名。

问题

我想使用implode('-'array_values($dobString)) 捕获dob_yeardob_monthdob_date 的结构为1997-12-01,然后将其保存到数据库中。

当我完成注册新用户的过程时,我收到未定义索引的错误消息:dob。

现在我也感觉到在 mutator 函数 setDobAttribute($dob) 中我在该函数代码中遗漏了一些东西,但似乎无法确定它是什么。

输入?建议?

提前谢谢你。

【问题讨论】:

  • implode(... array_values) 有点毫无意义。 implode 已经在处理数组的值,因此没有必要构建一个与 implode 无论如何都会得到完全相同的值的全新数组。
  • 使用php的日期函数。
  • 您在代码中的哪个位置将“dob”指向您的服务器,或者其他任何地方?
  • 您将$dob 传递给您的函数,但从不使用它。
  • @MarcB without array_values 它会给我一个数组到字符串转换的错误。在进一步研究 php 库 implode 时,它​​只允许 1 个胶水和 1 个变量,因此如果表单中有多个(在我的情况下为 3 个值以上)值,则需要一个数组循环来进行 implode。

标签: php sql laravel mutators


【解决方案1】:

使用array_map 可能...

private function setDobAttribute($dob){
  $keys = ['dob_year', 'dob_month', 'dob_date'];
  $this->attributes['dob'] = 
    implode('-', array_map(function($key) use($dob){
      return $dob[$key];
    }, $keys)); 
  return $this;
}

【讨论】:

    【解决方案2】:
    private function setDobAttribute(){
    
        $array = array('dob_year', 'dob_month', 'dob_date');
        return $this->attributes['dob'] = implode(-', $array);
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-19
      • 2011-09-20
      • 2020-03-27
      • 2014-12-02
      • 2011-07-20
      • 2015-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多