Convert POST to multidimensional array

試著忘記壹切 提交于 2021-01-29 15:30:34

问题


I have a form that creates a $_POST variable like:

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
)

and I would like to use PHP to convert it to a multidimensional array like:

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
        )

)

I know that I can make an array like this manually with this code:

$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"));

Thanks for helping me figure out how to do this the best way possible!


回答1:


Try this:

$result = array();

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

Demo




回答2:


The following code should work:

$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


来源:https://stackoverflow.com/questions/23038465/convert-post-to-multidimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!