你如何将 Laravel 查询结果转换为 json?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33716842/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:41:50  来源:igfitidea点击:

How do you convert Laravel query results to json?

phplaravel

提问by KingKongFrog

I have a query that I call with:

我有一个查询,我打电话给:

$query = "select * from myTable";
$results = DB::connection('myDB')->select($query);

I want to be able to get this in the simple json format of:

我希望能够以简单的 json 格式获得它:

[{firstColumn: firstColumnValue, secondColumn: secondColumnValue},
{firstColumn: firstColumnValue, secondColumn: secondColumnValue}]

What is the easiest way to achieve this?

实现这一目标的最简单方法是什么?

回答by Ruther Bergonia

As I have read here : Laravel, converting data from raw query to JSONyou can just use the json_encode. Hope that one helps.

正如我在这里读到的:Laravel,将数据从原始查询转换为 JSON,您只需使用 json_encode。希望有帮助。

回答by Sulthan Allaudeen

If you thought of writing web service or something related to it, then

如果您想编写 Web 服务或与之相关的内容,那么

$Response = array('success' => '1', 'result' => $yourData);
else
$Response = array('success' => '0', 'error' => 'Your Custom Errors');
return json_encode($Response);

So that you can handle it in while you retrieve according to the result.

以便您在根据结果检索时处理它。