Sunday, 5 April 2009

Prepare a request from an assoc.array

I am continuing (with sorry about this) to free from unused codes in my box. Meet next code - it allows to convert an assoc.array to an URL request and backward.
class PrepareRequest
{

    /**
     * string PrepareRequest::join(array $array)
     *
     * Converting of arrays to the strings. Resulting string contains keys and values
     * correctly for HTTP requests such as key1=value1&key2=value2...
     *
     */
    function join($array, $options=array())
    {
        static $defOptions = array(
            'fieldDelim' => '&',
            'valueDelim' => '=',
        );
        $options = array_merge($defOptions, $options);

        array_walk($array, array('PrepareRequest', '_join'), $options['valueDelim']);
        return implode($options['fieldDelim'], $array);
    }

    private function _join( & $value, $key, $delim2)
    {
        $value = $key . $delim2 . $value;
    }

    /**
     * array PrepareRequest::split(string $string)
     *
     * Parsing of string to associative array
     */
    function split($string, $options=array())
    {
        static $defOptions = array(
            'fieldDelim' => '&',
            'valueDelim' => '=',
        );
        $options = array_merge($defOptions, $options);

        $array = explode($options['fieldDelim'], $string);
        $result = array();
        for ($i = 0; $i < count($array); $i++)
        {
            list($key, $value) = explode($options['valueDelim'], $array[$i], 2);
            $result[$key] = $value;
        }
        return $result;
    }

}

/**
 * Example:
 */
$origin   = array('a' => 1, 'b' => 2, 'c' => 3);
$joined   = PrepareRequest::join($origin);
$splitted = PrepareRequest::split($joined);
print_r(array(
    'origin'   => $origin, 
    'joined'   => $joined, 
    'splitted' => $splitted, 
));

No comments:

Post a Comment