从多个复选框的Php数组
问题描述:
I'm working with laravel, and I'm a bit stuck in getting the right structure I want of the value, so I have a check box like this:
<input type="checkbox" name="permission[]" value="{{$permission->slug}}"> {{$permission->name}}
And this outputs me this:
array:2 [
0 => "dashboard.view"
1 => "user.edit"
]
But what I really need to store is something like this:
{"dashboard.view":true,"user.edit":true}
答
This should be what you're looking for:
<input type="checkbox" name="permission[{{$permission->slug}}]" value="true"> {{$permission->name}}
Should give you an associative array on the backend you can call json_encode
on if you need to store it as a json object.
答
You can use array_flip() function to exchange keys with values, and then to make json string you can call json_encode()