简体   繁体   English

Laravel-如何将数组保存到数据库

[英]Laravel - How to save an Array to Database

I have an array like this : 我有一个像这样的数组:

array:4 [▼
  "*name1*" => 1
  "*name2*" => 1
  "*name3*" => 2
  "*name4*" => 1
]

And I have an table Item with 'id'; 'name'; 'time' 我有一个带有'id'; 'name'; 'time'的表 'id'; 'name'; 'time' 'id'; 'name'; 'time'

Then how to I can save this array into Item Table using Laravel ? 然后如何使用Laravel将此数组保存到Item Table中?

I already do this but I know it's not working. 我已经这样做了,但是我知道它不起作用。 But I don't know how to save it 但是我不知道怎么保存

foreach ($data_participant[$i]['attributes']['stats']['itemGrants'] as $key => $value) {
      $itemGrants = new ItemGrant;
      $itemGrants->item = $key;
      $itemGrants->time = $value;

      $itemGrants->save();
}

Just simply use json_encode function to convert from array to JSON string. 只需使用json_encode函数从array转换为JSON字符串即可。 You may refer to this link for further information. 您可以参考此链接以获取更多信息。

For example, convert your array to JSON string format: 例如,将数组转换为JSON字符串格式:

$array = ["name"=>1,"name2"=>2,"name3"=>3];
$json_array = json_encode($array);

Now, the output will be a JSON string: 现在,输出将是JSON字符串:

[{"name":"1"},{"name2":"2"},{"name":"3"}];

You can save it to a database as a string in JSON format. 您可以将其作为JSON格式的字符串保存到数据库中。

If you want the data back in an array, then you have to decode. 如果要将数据放回数组中,则必须解码。 For example: 例如:

$string_json = "[{"name":"1"},{"name2":"2"},{"name":"3"}]";    
$array_output = json_decode($string_json,true);

Note the true boolean parameter passed to json_decode , this is important as without it json_decode will return an array of stdObject rather than an associative array. 请注意传递给json_decodetrue布尔参数,这很重要,因为如果没有json_decode它将返回stdObject数组而不是关联数组。

Now, you can get back the array as your input. 现在,您可以取回数组作为输入。

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

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