【问题标题】:How can convert query string in laravel to json如何将laravel中的查询字符串转换为json
【发布时间】:2020-04-10 23:36:32
【问题描述】:

这里有个问题,想把收到的查询字符串改成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);

如果没有查询字符串,我也想更改,那么结果是 {}

【问题讨论】:

    标签: php json laravel laravel-5


    【解决方案1】:
    //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);
    

    有任何问题欢迎评论

    【讨论】:

      【解决方案2】:

      这两种情况都应该适合你:

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

      PHP Manual - JSON Functions - json_encode

      Laravel 5.8 Docs - Requests - Retrieving Input - Retrieving Input From The Query Stringquery

      【讨论】:

      • 它工作得很好,但是如果没有查询字符串条件,那么它会生成 {}
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      • 2022-01-08
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-08
      相关资源
      最近更新 更多