如何在 Laravel 中将数组作为 URL 参数传递?
laravelphpserver side programming更新于 2025/4/29 23:07:17
要将数组作为 URL 参数传递,您可以使用 PHP 内置函数 http_build_query()。http_build_query() 返回 URL 编码的查询字符串。
示例 1
使用 http_build_query()
以下是此方法的示例 -
$data = array( 'field1' => 'test', 'field2' => 'xyz' ); echo http_build_query($data) . "
";
输出
上述代码的输出是 −
field1=test&field2=xyz
以下示例显示当您有一个数组并且需要将其作为 URL 参数传递时如何使用 http_build_query()。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Http\Response; class UserController extends Controller{ public function index(Request $request) { $yoururl = "https://www.test.com"; $params = array( "t1" => "abc", "t2" => "xyz" ); echo $yourfinalurl = $yoururl."?".http_build_query($params); } }
上述代码的输出是 −
https://www.test.com?t1=abc&t2=xyz
示例 2
您可以使用 PHP 内置函数 serialize() 和 urlencode 将数组作为 URL 参数传递。
serialize() 函数将返回给定输入的位序列,然后 urlencode 将再次对这些值以及其中的特殊字符进行编码。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Http\Response; class UserController extends Controller{ public function index(Request $request) { $yoururl = "https://www.test.com"; $params = array( "t1" => "abc", "t2" => "xyz" ); $firstserialize = serialize($params); echo $yourfinalurl = $yoururl."?".urlencode($firstserialize); } }
输出
上述代码的输出是 −
https://www.test.com?a%3A2%3A%7Bs%3A2%3A%22t1%22%3Bs%3A3%3A%22abc%22%3Bs%3A2%3A%22t2%22%3Bs%3A3%3A%22xyz%22%3B%7D
示例 3
使用 http_build_query() 和 urlencode() 函数。
urlencode() − 它会将值编码为字符串。
http_build_query() − 返回 URL 编码的查询字符串。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Http\Response; class UserController extends Controller{ public function index(Request $request) { $yoururl = "https://www.test.com"; $params = array( "t1" => "abc", "t2" => "xyz" ); echo $yourfinalurl = $yoururl."?".urlencode(http_build_query($params)); } }
输出
上述代码的输出是 −
https://www.test.com?t1%3Dabc%26t2%3Dxyz
示例 4
使用 urlencode() 和 jsonencode()
以下是使用 jsconencode() 和 urlencode() 函数将数组作为 URL 参数传递的示例 -
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Http\Response; class UserController extends Controller{ public function index(Request $request) { $yoururl = "https://www.test.com"; $params = array( "t1" => "abc", "t2" => "xyz" ); echo $yourfinalurl = $yoururl."?".urlencode(json_encode($params)); } }
输出
上述代码的输出是 −
https://www.test.com?%7B%22t1%22%3A%22abc%22%2C%22t2%22%3A%22xyz%22%7D

