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'
Then how to I can save this array into Item Table using Laravel ?
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. You may refer to this link for further information.
For example, convert your array to JSON string format:
$array = ["name"=>1,"name2"=>2,"name3"=>3];
$json_array = json_encode($array);
Now, the output will be a JSON string:
[{"name":"1"},{"name2":"2"},{"name":"3"}];
You can save it to a database as a string in JSON format.
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.
Now, you can get back the array as your input.