PHP - 将数组插入http_build_query()

时间:2013-04-29 02:38:26

标签: php

$array = array('username' => 'mainytype','password' => 'abc1234','phone' =>     '7023451287');
$count = 0;

foreach($array as $k => $v){
   $count++;
   $new_data['info'.$count] = array("input[$k]=".$v);
}


print_r($new_data);

$ty = http_build_query($new_data);
print_r($ty);

?>

// print_r($new_data):
 Array ( [info1] => Array ( [0] => input[username]=mainytype ) [info2] => Array ( [0]     => input[password]=abc1234 ) [info3] => Array ( [0] => input[phone]=7023452134 ) ) 

//print_r($ty);
info1%5B0%5D=input%5Busername%5D%3Dmainytype&info2%5B0%5D=input%5Bpassword    %5D%3Dabc1234&info3%5B0%5D=input%5Bphone%5D%3D7023452134

我猜foreach构建了3个独立的数组。我理解http_build_query()的结果,但我希望它看起来像这样:

input%5Busername%5D=mainytype&input%5Bpassword%5D=abc1234&input%5Bphone%5D=7023451287

2 个答案:

答案 0 :(得分:2)

试试这个

<?php
$array = array('username' => 'mainytype','password' => 'abc1234','phone' =>     '7023451287');

foreach($array as $k => $v){
  $new_data["input[$k]"] = $v;
}


print_r($new_data);

$ty = http_build_query($new_data);
echo($ty);

?>

答案 1 :(得分:1)

这可以为您提供所需的结果:

$array = array(
    'username' => 'mainytype',
    'password' => 'abc1234',
    'phone'    => '7023451287'
);

$new_data = array('input' => $array);

print_r($new_data);

$ty = http_build_query($new_data);
echo($ty);

http_build_query对嵌套数组没有任何问题。