【问题标题】:laravel get array from text in voyagerlaravel 从 voyager 中的文本获取数组
【发布时间】:2019-09-20 09:28:08
【问题描述】:

试图将文本保存为数据库中的数组,所以我写了

  some Text
  some Text,
  some Text;
  some Text.

它在数据库中保存为

        ["some Text\r\nsome Text,\r\nsome Text;\r\nsome Text."]

我怎样才能以这种格式保存它

        ["some Text" ,"some Text,","some Text;" , "some Text."]

有没有休息什么的

protected $casts = [
'array_value' => 'array',
];


public function setArrayValueAttribute($value)
{
    $this->attributes['array_value'] = json_encode($value);
}

public function getArrayValueAttribute($value)
{
    return collect(json_decode($value));
}

【问题讨论】:

    标签: php json laravel laravel-5 eloquent


    【解决方案1】:

    我遇到了完全相同的问题,并通过使用 textvarchar 作为数据库列类型而不是 JSON 来修复它。我知道这有点脏,但对我有用

    【讨论】:

      【解决方案2】:

      你可以在 setter 中暴力破解它。

      public function setArrayValueAttribute($value)
      {
          $newArray = [];
          foreach($value as $item) {
              $items = explode("\r\n", $item);
              array_push($newArray, $items);
          }
      
          $this->attributes['array_value'] = json_encode($newArray);
      }
      

      但这仅适用于您上面的示例用例。如果您期待任何其他类型的换行符,您也必须处理它们。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-07
        • 1970-01-01
        • 1970-01-01
        • 2020-09-30
        • 1970-01-01
        • 1970-01-01
        • 2020-08-21
        相关资源
        最近更新 更多