PHP - 从 URL 获取索引 URL 查询字符串参数

像 cid 这样的独立参数很容易获得,但是像category1和category2这样的索引查询字符串参数是我陷入困境的地方。

我还可以选择以 JSON 格式发送 webhook(如果这更有意义),但仍然不确定如何获取 itemsku1 和 itemsku2 等索引参数。

我还忘了提及,索引参数可能会根据购买的产品数量而变化,所以我事先不知道 URL 中会有多少个。

提前致谢!


尚方宝剑之说
浏览 104回答 3
3回答

慕娘9325324

尝试这样的事情<?php$param_names = [&nbsp; &nbsp; 'amount',&nbsp; &nbsp; 'category',&nbsp; &nbsp; 'itemsku',&nbsp; &nbsp; 'quantity',];$data = [];foreach ($_GET as $key => $val) {&nbsp; &nbsp; foreach ($param_names as $param_name) {&nbsp; &nbsp; &nbsp; &nbsp; if (strpos($key, $param_name) === 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $idx = substr($key, strlen($param_name), 1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $data[$idx][$param_name] = $val;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}var_dump($data);这是结果array (size=2)&nbsp; 1 =>&nbsp;&nbsp; &nbsp; array (size=3)&nbsp; &nbsp; &nbsp; 'amount' => string '233.55' (length=6)&nbsp; &nbsp; &nbsp; 'category' => string 'clothing' (length=8)&nbsp; &nbsp; &nbsp; 'itemsku' => string '01235654' (length=8)&nbsp; &nbsp; &nbsp; 'quantity' => string '1' (length=1)&nbsp; 2 =>&nbsp;&nbsp; &nbsp; array (size=4)&nbsp; &nbsp; &nbsp; 'amount' => string '156.99' (length=6)&nbsp; &nbsp; &nbsp; 'category' => string 'accessories' (length=11)&nbsp; &nbsp; &nbsp; 'itemsku' => string '525124' (length=6)&nbsp; &nbsp; &nbsp; 'quantity' => string '3' (length=1)

MMTTMM

我不确定我是否正确理解你,但你不能使用:$category1 = filter_input(INPUT_GET,"category1",FILTER_SANITIZE_STRING);$category2 = filter_input(INPUT_GET,"category2",FILTER_SANITIZE_STRING);$sku1 = filter_input(INPUT_GET,"itemsku1",FILTER_SANITIZE_STRING);$sku2 = filter_input(INPUT_GET,"itemsku2",FILTER_SANITIZE_STRING);依此类推...除非您不知道索引参数的确切数量,否则您可以使用以下命令,它将参数存储在数组中。$query&nbsp; = explode('&', $_SERVER['QUERY_STRING']);$params = array();foreach( $query as $param ){&nbsp; list($name, $value) = explode('=', $param, 2);&nbsp; $params[urldecode($name)][] = urldecode($value);}假设您要访问链接https://example.com/page.php?itemsku=test1&itemsku=test2$params['itemsku'][0]将返回:test1 $params['itemsku'][1]将返回:test2要循环遍历itemsku参数数组,只需执行以下操作:foreach($params['itemsku'] as $sku){&nbsp; &nbsp;echo $sku . "\n";}会输出:test1test2

HUWWW

我不确定我是否理解正确,但你可以使用parse_url. 在你的情况下:$url = 'https://example.com/page.php?cid=123456&eventid=965254&trackerid=2523654&amount1=233.55&amount2=156.99&catgory1=clothing&category2=accessories&itemsku1=01235654&itemsku2=525124&quantity1=1&quantity2=3';$temp_array = [];parse_str(parse_url($url, PHP_URL_QUERY), $temp_array);var_dump($temp_array);这将生成一个包含所有查询参数的数组。然后您可以访问每个参数,例如:echo $temp_array['cid'];echo $temp_array['catgory1'];echo $temp_array['catgory2'];echo $temp_array['itemsku1'];echo $temp_array['itemsku2'];
打开App,查看更多内容
随时随地看视频慕课网APP