使用数组数据构建查询字符串 [英] Build query string with array data
问题描述
我向函数传递了一个包含一些答案的对象。然后,我执行以下操作来创建关联数组
I pass my function an object that contains some answers. I then do the following to create an associative array
$field_data = array();
foreach($submission->answers as $answer) {
$field_data[$answer->question_id] = $answer->text + 1;
}
结果会像这样
array:15 [▼
1 => 3
2 => 4
3 => 2
4 => 5
]
我需要做的就是使用上述数据构建一个API调用。 API URL看起来像这样
What I need to do is build an API call using the above data. The API URL would look something like this
someAPI.com?api.php?function=calculatePrice&question 1 > = 3 & question2 = 4& question3 = 2& question4 = 5
someAPI.com?api.php?function=calculatePrice&question1=3&question2=4&question3=2&question4=5
问题编号在哪里是数组左侧的值,=符号后面的部分是数组右侧的值。
Where the question number is the value on the left side of the array, and the part after the = sign is the value on the right of the array.
什么是最好的方法?
谢谢
推荐答案
这可以通过 http-build-query 方法本身来实现的PHP。第二个参数接受前缀加在键之前。
密钥应为数字类型
This can be achieved with the http-build-query method itself of php. The second param accepts the prefix to prepend to the key. The key should be of numeric type
您可以使用 http-build-query
根据您的情况
You can use the http-build-query
like this in your case
http_build_query($field_data, 'question');
这篇关于使用数组数据构建查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!