1

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();
}
10
  • What's the error ? or array $data_participant[$i]['attributes']['stats']['itemGrants'] might be empty ? Commented Jul 30, 2017 at 6:23
  • Is ItemGrant is an eloquent model?If yes, which table is represented by the model? Commented Jul 30, 2017 at 6:27
  • Hello @SagarGautam : No it's not empty. It's array as I was writing above. There is no error happens. But it not save to database. Commented Jul 30, 2017 at 6:28
  • Hello @MASh : Yes, it's an eloquent model. The table is "Item" as I was writing. Commented Jul 30, 2017 at 6:31
  • 1
    Hello all guys, this is my mistake. I forgot check my grammar table name in protected $table. My bad. I'm sorry. Thank for your time. Commented Jul 30, 2017 at 6:47

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.