繁体   English   中英

如何将laravel中的查询字符串转换为json

[英]How can convert query string in laravel to json

我这里有个问题,我想把我收到的查询字符串改成json形式如下

{"id":"89"}

在这里我尝试使用 json_encode 但它产生的是

""?id=89""

这是我的代码

    $coba = str_replace($request->url(), '',$request->fullUrl());
        if (empty($coba)) {
           $url = "{}";
        } else {
            $url = $coba;
        }

         $json_body = json_encode($url);

如果没有查询字符串,我还想更改结果为 {}

这应该为你做这两种情况:

json_encode($request->query(), JSON_FORCE_OBJECT);

PHP 手册 - JSON 函数 - json_encode

Laravel 5.8 文档 - 请求 - 检索输入 - 从查询字符串query检索输入

//get Parameters
$array = [
    'id' => 20,
    'name' => 'john',
];
//getting the current url from Request
$baseUrl = $request->url();

//we are encoding the array because 
//u said that the get parms in json format
//so that ...
$json = json_encode($array);

//now building the query based on the data
//from json by decoding it
$query = (http_build_query(json_decode($json)));

//at the end of the url you need '?' mark so...
$url = \Illuminate\Support\Str::finish($baseUrl,'?');
//now Merging it
$fullUrl = $url.$query;

dump($fullUrl);

对于任何问题,请发表评论

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM