http_build_query生成 url-encoded 以後的請求字符串php
一、使用鍵值對,關聯數組:數組
<?php $data = array('foo'=>'bar', 'baz'=>'boom', 'cow'=>'milk', 'php'=>'hypertext processor'); echo http_build_query($data); /* 輸出: foo=bar&baz=boom&cow=milk&php=hypertext+processor */ ?>
二、使用數字下標ui
<?php $data = array('foo', 'bar', 'baz', 'boom', 'cow' => 'milk', 'php' =>'hypertext processor'); echo http_build_query($data); /* 輸出: 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 */ ?>
三、使用多維數組:this
<?php $data = array('user'=>array('name'=>'Bob Smith', 'age'=>47, 'sex'=>'M', 'dob'=>'5/12/1956'), 'pastimes'=>array('golf', 'opera', 'poker', 'rap'), 'children'=>array('bobby'=>array('age'=>12, 'sex'=>'M'), 'sally'=>array('age'=>8, 'sex'=>'F')), 'CEO'); echo http_build_query($data, 'flags_'); /* 輸出:(爲了可讀性對其進行了折行) user[name]=Bob+Smith&user[age]=47&user[sex]=M&user[dob]=5%1F12%1F1956& pastimes[0]=golf&pastimes[1]=opera&pastimes[2]=poker&pastimes[3]=rap& children[bobby][age]=12&children[bobby][sex]=M&children[sally][age]=8& children[sally][sex]=F&flags_0=CEO 注意:只有基礎數組中的數字下標元素「CEO」才獲取了前綴,其它數字下標元素(如 pastimes 下的元素)則不須要爲了合法的變量名而加上前綴。 */ ?>
四、使用對象url
<?php class myClass { var $foo; var $baz; function myClass() { $this->foo = 'bar'; $this->baz = 'boom'; } } $data = new myClass(); echo http_build_query($data); /* 輸出: foo=bar&baz=boom */ ?>