如何将 Laravel 集合数组转换为 json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46274135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Laravel collection array to json
提问by Khirad Banu
How can i convert this Laravel collection array to json format like below.
如何将此 Laravel 集合数组转换为 json 格式,如下所示。
//All records from users table.
$users = DB::table('users')->get();
// Required json format.
return '{
"data": [
{
"DT_RowId": "row_1",
"id": "Tiger",
"clear": "Nixon",
"fsssf": "System Architect",
"tex": "[email protected]",
"created_at": "Edinburgh",
"updated_at": "Edinburgh"
},
{
"DT_RowId": "row_2",
"id": "Tiger",
"clear": "Nixon",
"fsssf": "System Architect",
"tex": "[email protected]",
"created_at": "Edinburgh",
"updated_at": "Edinburgh"
}
],
"options": [],
"files": []
}';
Sorry for the basic question,but i am unable to convert this into this jso.
对不起,基本问题,但我无法将其转换为这个jso。
回答by Asim Shahzad
Have a look at the documentation.
查看文档。
You can use toJson(),to convert the collection to json object.
您可以使用 toJson() 将集合转换为 json 对象。
$users = DB::table('users')->get()->toJson();
dd($users);
You can also can do this in simple php way by using json_encode function
您也可以使用 json_encode 函数以简单的 php 方式执行此操作
$users = json_encode($users);
Have a look at this link
看看这个链接
Greetings and happy coding!
问候和快乐的编码!
回答by Yevgeniy Afanasyev
If you are looking into doing if for a blade template you can use the @jsonBlade directive, like so:
如果您正在考虑为刀片模板做 if,您可以使用@jsonBlade 指令,如下所示:
<script type="text/javascript">
var PARAMS = @json($params)
</script>
P.S.Tested in Laravel 5.6
PS在 Laravel 5.6 中测试
回答by Gaurav Gupta
add "use Response;"
添加“使用响应;”
return Response::json([
'data' => $value
], 200);
hope this helps!
希望这可以帮助!
回答by Tarun Saini
if we you laravel 5.5 then you should use eloquent-resources
如果我们是 laravel 5.5,那么你应该使用 eloquent-resources
回答by Muaaz Rafi
Couple of things you can do, you can use default method ->toJson() with the user collection like this
你可以做几件事,你可以使用默认方法 ->toJson() 和这样的用户集合
$users = DB::table('users')->get();
$users-toJson();
If you do have troubles with it them you can php build in json_encode method here is the full documentation http://php.net/manual/en/function.json-encode.php
如果您确实遇到问题,您可以在 json_encode 方法中构建 php,这里是完整的文档http://php.net/manual/en/function.json-encode.php
$users = DB::table('users')->get();
json_encode($users)
Hope this helps!
希望这可以帮助!

