Programing

배열에서 쿼리 문자열을 작성하는 PHP 함수

lottogame 2020. 6. 7. 00:41
반응형

배열에서 쿼리 문자열을 작성하는 PHP 함수


키 값 쌍의 배열에서 쿼리 문자열을 작성하는 PHP 함수의 이름을 찾고 있습니다. 이 작업을 수행 하기 위해 내장 PHP 기능을 찾고 있습니다 . 홈 브룩 기능이 아닙니다 (Google 검색이 모두 반환되는 것 같습니다). 하나만 있습니다. 이름을 기억하지 못하거나 php.net에서 찾을 수 없습니다. IIRC의 이름은 그렇게 직관적이지 않습니다.


찾고 있습니다 http_build_query().


다음은 간단한 php4 친화적 인 구현입니다.

/**
* Builds an http query string.
* @param array $query  // of key value pairs to be used in the query
* @return string       // http query string.
**/
function build_http_query( $query ){

    $query_array = array();

    foreach( $query as $key => $key_value ){

        $query_array[] = urlencode( $key ) . '=' . urlencode( $key_value );

    }

    return implode( '&', $query_array );

}

@thatjuan의 답변 외에도 .
더 호환되는 PHP4 버전 :

if (!function_exists('http_build_query')) {
    if (!defined('PHP_QUERY_RFC1738')) {
        define('PHP_QUERY_RFC1738', 1);
    }
    if (!defined('PHP_QUERY_RFC3986')) {
        define('PHP_QUERY_RFC3986', 2);
    }
    function http_build_query($query_data, $numeric_prefix = '', $arg_separator = '&', $enc_type = PHP_QUERY_RFC1738)
    {
        $data = array();
        foreach ($query_data as $key => $value) {
            if (is_numeric($key)) {
                $key = $numeric_prefix . $key;
            }
            if (is_scalar($value)) {
                $k = $enc_type == PHP_QUERY_RFC3986 ? urlencode($key) : rawurlencode($key);
                $v = $enc_type == PHP_QUERY_RFC3986 ? urlencode($value) : rawurlencode($value);
                $data[] = "$k=$v";
            } else {
                foreach ($value as $sub_k => $val) {
                    $k = "$key[$sub_k]";
                    $k = $enc_type == PHP_QUERY_RFC3986 ? urlencode($k) : rawurlencode($k);
                    $v = $enc_type == PHP_QUERY_RFC3986 ? urlencode($val) : rawurlencode($val);
                    $data[] = "$k=$v";
                }
            }
        }
        return implode($arg_separator, $data);
    }
}

그러나이 작업의 역을 위해 다음을 사용할 수 있습니다.

void parse_str(str $input, array $output);
//for example:
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

행운을 빕니다.


이 질문은 꽤 오래되었고 PHP의 경우 (현재) 매우 인기있는 PHP 프레임 워크 Laravel에서 수행하는 방법이 있습니다.

To encode the query string for a path in your application, give your routes names and then use the route() helper function like so:

route('documents.list.', ['foo' => 'bar']);

The result will look something like:

http://localhost/documents/list?foo=bar

Also be aware that if your route has any path segment parameters e.g. /documents/{id}, then make sure you pass an id argument to the route() parameters too, otherwise it will default to using the value of the first parameter.


Implode will combine an array into a string for you, but to make an SQL query out a kay/value pair you'll have to write your own function.

참고URL : https://stackoverflow.com/questions/400805/php-function-to-build-query-string-from-array

반응형