将POST转换为多维数组

时间:2014-04-13 02:31:28

标签: php multidimensional-array

我有一个创建$ _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"));

感谢您帮助我找出如何以最佳方式做到这一点!

2 个答案:

答案 0 :(得分:1)

试试这个:

$result = array();

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

Demo

答案 1 :(得分:0)

以下代码应该有效:

$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