问题
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