php Laravel,将数据从原始查询转换为 JSON

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

Laravel, converting data from raw query to JSON

phpjavascriptlaravel

提问by Srle

Hy all, can anyone help me with converting some data which will be return from model(based on the RAW query) into JSON.

大家好,谁能帮我将一些将从模型(基于 RAW 查询)返回的数据转换为 JSON。

So in my controller i have something like:

所以在我的控制器中,我有类似的东西:

public function get_index() {
    $data = Something::getDataFromRawQuery();

    return View::make('....')->with('data', $data);
}

So my question is how to forward JSON data to the view from controller?

所以我的问题是如何将 JSON 数据从控制器转发到视图?

Here is the query:

这是查询:

$apps = DB::query('SELECT a.name,
    a.desc,
    a.sig,
    ar.rate
    FROM something a
    INNER JOIN something_else ar
    ON (a.id=ar.something_id)
    ORDER BY ar.rate DESC'
 );

 return $apps;

回答by Joseph Silber

DB::queryreturns a simple array, so just call json_encodedirectly on it:

DB::query返回一个简单的数组,所以直接调用json_encode它:

$data = Something::getDataFromRawQuery();

return View::make('....')->with('data', json_encode($data));

回答by Gary Green

Just use json_encode()

只需使用 json_encode()

public function get_index() {
    $data = Something::getDataFromRawQuery();

    /* Do your loop here to build an array "results" from $data, if necessary
       Really depends on what ::getDataFromRawQuery returns. */

    return View::make('....')->with('data', json_encode($results));
}