I want to construct this url using http_build_query:
https://www.googleapis.com/freebase/v1/topic/m/0d6lp?filter=/common/topic/notable_for&filter=/common/topic/alias
Please note that the "filter=" parameter comes twice in the url, to specify two filters.
I tried to do it this way but having a problem:
$service_url = 'https://www.googleapis.com/freebase/v1/topic';
$mid = '/m/0d6lp';
$params = array('filter' => '/common/topic/notable_for', 'filter' => '/common/topic/alias');
$url = $service_url . $mid . '?' . http_build_query($params);
The problem is as 'filter' array key repeats twice, only the last parameter appears in the http_build_query. How do I construct the original url with two filters?
The problem here of course is that every key in a PHP array (hash) can only have one value. Intrinsically, a PHP hash is not a good representation of a querystring, because the query string has an order and has no constraints about the uniqueness of the keys.
To combat this, you'll need a special querystring builder that can handle duplicate keys:
class QueryString {
private $parts = array();
public function add($key, $value) {
$this->parts[] = array(
'key' => $key,
'value' => $value
);
}
public function build($separator = '&', $equals = '=') {
$queryString = array();
foreach($this->parts as $part) {
$queryString[] = urlencode($part['key']) . $equals . urlencode($part['value']);
}
return implode($separator, $queryString);
}
public function __toString() {
return $this->build();
}
}
Example usage (Codepad Demo):
$qs = new QueryString();
$qs->add('filter', '1');
$qs->add('filter', '2');
var_dump($qs->build()); // filter=1&filter=2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With