带有数组url参数 [英] passing arrays as url parameter

查看:341
本文介绍了带有数组url参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是我可以通过一个数组作为url参数的最佳方式?我在想,如果这是可能的:

what is the best way that i can pass an array as a url parameter? i was thinking if this is possible:

$aValues = array();

$url = 'http://www.example.com?aParam='.$aValues;

或这个怎么样:

$url = 'http://www.example.com?aParam[]='.$aValues;

香港专业教育学院读的例子,但我觉得凌乱:

Ive read examples, but i find it messy:

$url = 'http://www.example.com?aParam[]=value1&aParam[]=value2&aParam[]=value3';

先谢谢了。

推荐答案

编辑:不要错过下面斯特凡的解决方案,它使用了非常方便的 http_build_query() 功能: HTTP:/ /stackoverflow.com/a/1764199/179125

Don't miss Stefan's solution below, which uses the very handy http_build_query() function: http://stackoverflow.com/a/1764199/179125

knittl是正确的约逃跑。然而,有一个简单的方法来做到这一点:

knittl is right on about escaping. However, there's a simpler way to do this:

$url = 'http://example.com/index.php?';
$url .= 'aValues[]=' . implode('&aValues[]=', array_map('urlencode', $aValues));

如果你想用一个关联数组要做到这一点,试试这个来代替:

If you want to do this with an associative array, try this instead:

PHP 5.3 + (lambda函数)

PHP 5.3+ (lambda function)

$url = 'http://example.com/index.php?';
$url .= implode('&', array_map(function($key, $val) {
    return 'aValues[' . urlencode($key) . ']=' . urlencode($val);
  },
  array_keys($aValues), $aValues)
);

PHP< 5.3 (回调)

function urlify($key, $val) {
  return 'aValues[' . urlencode($key) . ']=' . urlencode($val);
}

$url = 'http://example.com/index.php?';
$url .= implode('&', array_map('urlify', array_keys($aValues), $aValues));

这篇关于带有数组url参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆