我正在尝试从特定API获取一些数据。如果我在API页面上进行测试运行,他们会将这个url作为响应返回给我,所以我可以从那里获取api数据:
(仅限分类摘要)
getUploads(): Observable<UploadModel[]> {
this.http.get(UPLOADS_ENDPOINT)
.map((response: Response) => {
// parse the json response here, and return an array of UploadModels
});
}
基本上意味着:1,2,3,4,5,6,7,8,9,10,11,12
我有一个类别数组,还有12个元素。
数组如下所示:
&categories=1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%2C10%2C11%2C12"
从我的系统发出api请求,我调用的url必须具有与api测试相同的标准。但是,这就是我的URL的样子(只有类别片段)
dd($this->categories) outputs:
array:12 [▼
0 => "1"
1 => "2"
2 => "3"
3 => "4"
4 => "5"
5 => "6"
6 => "7"
7 => "8"
8 => "9"
9 => "10"
10 => "11"
11 => "12"
]
代码段:
&categories=%5B%221%22%2C%222%22%2C%223%22%2C%224%22%2C%225%22%2C%226%22%2C%227%22%2C%228%22%2C%229%22%2C%2210%22%2C%2211%22%2C%2212%22%5D
正如您所看到的,api测试的url片段比我的短得多。我认为那是因为编码?
我尝试先将数组转换为json并使用rawurlencode方法解决它。但这并没有解决我的问题。我需要以同样的方式“转换”网址,api会这样做。
有谁知道如何解决这个问题?
我找到了什么:
我发现这个片段几乎解决了我的问题
$categories = "&categories=" . rawurlencode(json_encode($this->categories));
结果如下:
$categories = "&categories=" . http_build_query($this->categories, null, "%2C", PHP_QUERY_RFC1738);
但是我真的不知道开头的ne 0来自哪里以及为什么每个数组元素之后总是有一个“=”字符
答案 0 :(得分:0)
如果您检查变量,您会发现该网址编码与此问题无关:
var_dump(rawurldecode('categories=%5B%221%22%2C%222%22%2C%223%22%2C%224%22%2C%225%22%2C%226%22%2C%227%22%2C%228%22%2C%229%22%2C%2210%22%2C%2211%22%2C%2212%22%5D'));
string(63) "categories=["1","2","3","4","5","6","7","8","9","10","11","12"]"
请比较:
$categories = array('1', '2', '3');
var_dump(json_encode($categories));
var_dump(implode(',', $categories));
string(13) "["1","2","3"]"
string(5) "1,2,3"
http_build_query()
在这里太过分了。你真的没有任何复杂的结构,只有一个字符串变量。