将POST转换为多维数组



我有一个创建$_POST变量的表单,如:

Array
(
    [submit] => Update the List!
    [12052,s] => 1
    [12052,d] => 0
    [12052,r] => 1
    [11271,s] => 1
    [11271,d] => 0
    [11271,r] => 5
    [16008,s] => 0
    [16008,d] => 0
    [16008,r] => 4
)

我想用PHP把它转换成一个多维数组,比如:

Array
(
    [12052] => Array
        (
            [s] => 1
            [d] => 0
            [r] => 1
        )
    [11271] => Array
        (
            [s] => 1
            [d] => 0
            [r] => 5
        )
    [16008] => Array
        (
            [s] => 0
            [d] => 0
            [r] => 4
        )
)

我知道我可以用以下代码手动制作这样的数组:

$test = array("12052" => array("s"=>"1","d"=>"0","r"=>"1"),"11271" => array("s"=>"1","d"=>"0","r"=>"5"),"16008" => array("s"=>"0","d"=>"0","r"=>"4"));

谢谢你帮我找出最好的方法!

试试这个:

$result = array();
foreach ($_POST as $key => $value) {
    if ($key !== 'submit') {
        $key = strtok($key, ','); // remove everything after ','
        $result[$key][] = $value;
    }    
}

演示

以下代码应该可以工作:

$arr = array();
foreach(array_diff_key($_POST, array("submit" => "")) as $key => $val){
    $exp = explode(",", $key, 2);
    $arr[$exp[0]][$exp[1]] = $val;
}
print_r($arr); // Outputs the multidimensional array

相关内容

  • 没有找到相关文章

最新更新