http_build_query 数组转 query

最后更新于:2022-04-02 02:28:50

[TOC] ## 实例 ### 基础实例 ``` $data = ['foo' => 'bar', 'baz' => 'boom', 'cow' => ['milk', 'aaa'], ]; // 进行了自动 urlencode 转义 echo $query = http_build_query($data) . "\n"; //foo=bar&baz=boom&cow%5B0%5D=milk&cow%5B1%5D=aaa&php=hypertext+processor echo urldecode($query); //foo=bar&baz=boom&cow[0]=milk&cow[1]=aaa&php=hypertext processor ``` ### 自定义分隔符 ``` $data = ['foo' => 'bar', 'baz' => 'boom', 'cow' => ['milk', 'aaa'], 'php'=>'hypertext processor', ]; //自定义分隔符 echo $query = http_build_query($data, '' ,'&')."\n"; //foo=bar&baz=boom&cow%5B0%5D=milk&cow%5B1%5D=aaa&php=hypertext+processor echo urldecode($query); //foo=bar&baz=boom&cow[0]=milk&cow[1]=aaa&php=hypertext processor ``` ### 自定义数组下标 ``` $data = array('foo', 'bar', 'baz', 'boom', 'cow' => 'milk', 'php' =>'hypertext processor'); echo http_build_query($data) . "\n"; // 0=foo&1=bar&2=baz&3=boom&cow=milk&php=hypertext+processor echo http_build_query($data, 'myvar_'); // myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk&php=hypertext+processor ```
';