Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP http_build_query with two array keys that are same

Tags:

php

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?

like image 771
Ninja Avatar asked Jun 18 '13 05:06

Ninja


1 Answers

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
like image 193
Bailey Parker Avatar answered Oct 14 '22 13:10

Bailey Parker