我需要将每个数组的每个值添加到像人一样的新数组上。
<div class="person">
<input name="name[]">
<input name="type[]">
</div>
<div class="person">
<input name="name[]">
<input name="type[]">
</div>
可能是两个人,还有十个人是多动态的。
$ _ POST返回:
Array( [name] => Array([0] => oliver [1] => tom) [type] => Array([0] => developer [1] => designer) )
我希望两个人分开,但我没有尝试:
$person1 = array(
"name" => "oliver"
"type" => "developer"
)
$person2 = array(
"name" => "tom"
"type" => "designer"
)
答案 0 :(得分:2)
$arr['name'] = $_POST['name'];
$arr['type'] = $_POST['type'];
array_unshift($arr, null);
print_r(call_user_func_array('array_map', $arr));
输出:
Array
(
[0] => Array
(
[0] => Oliver
[1] => developer
)
[1] => Array
(
[0] => Tom
[1] => designer
)
)
答案 1 :(得分:0)
尝试以下方法:
$people = array(); // define new array
// first loop to find the minimal size array - this will prevent errors down the road.
$minIndex = 0;
foreach($_POST as $key=>$value)
if(is_array($value)){
$currentSize = sizeof($value); // get the current data array length
if(($minIndex==0) || ($minIndex > $currentSize))
$minIndex = $currentSize; // finds the minimus array length
}
//populate the $people array
for($i = 0; $i < $minIndex; $i++){ // loop until $minIndex to prevent errors
$current = array(); // this is the current person
foreach($_POST as $key=>$value) // loop through all $_POST arrays
if(is_array($value)) // only if this is an array
$current[$key] = $value[$i]; // add the current data to the current person
array_push($people,$current);
}
print_r($people); // print all people
对于您的示例,这将打印:
Array(
[0] => Array([name] => oliver [type] => developer)
[1] => Array([name] => tom [type] => designer)
)
所以你可以达到这样的人的详细信息:$people[0]['name']
,$people[0]['type']
等。
答案 2 :(得分:0)
对您的输入元素进行分组,让PHP为您创建数组!
<?php
if (isset($_POST['submit'])) {
echo "<pre>";
print_r($_POST);
echo "</pre>";
}
?>
<form method="post">
<div class="person">
<input name="person[0][name]" value="Fred">
<input name="person[0][type]" value="Developer">
</div>
<div class="person">
<input name="person[1][name]" value="Alex">
<input name="person[1][type]" value="Designer">
</div>
<input type="submit" value="submit" name="submit"/>
</form>
答案 3 :(得分:0)
无论您有多少名称和类型,将两个关联数组输入array_map()
都将根据需要重组/转置数据。
代码:(Demo)(或者如果您需要子数组中的关联键:Demo)
var_export(array_map(function($n, $t){return [$n, $t];}, $_POST['name'], $_POST['type']));
例如:
$_POST = ['name' => ['oliver', 'tom'], 'type' => ['developer', 'designer']];
成为:
array (
0 =>
array (
0 => 'oliver',
1 => 'developer',
),
1 =>
array (
0 => 'tom',
1 => 'designer',
),
)
和
$_POST = ['name' => ['oliver', 'tom', 'mitchel'], 'type' => ['developer', 'designer', 'artist']];
成为:
array (
0 =>
array (
0 => 'oliver',
1 => 'developer',
),
1 =>
array (
0 => 'tom',
1 => 'designer',
),
2 =>
array (
0 => 'mitchel',
1 => 'artist',
),
)