修复多维foo [a] [] [b]数组输入

时间:2011-10-09 15:40:03

标签: php

我在html中使用多维输入标签:

Car 1
<input name="warehouse[cars][][name]" />
<input name="warehouse[cars][][model]" />
<input name="warehouse[cars][][year]" />

Car 2
<input name="warehouse[cars][][name]" />
<input name="warehouse[cars][][model]" />
<input name="warehouse[cars][][year]" />

问题在于我在PHP方面得到了一些混乱的数组:

Array:warehouse->cars
(
    [0] => Array
        (
            [name] => Audi,
            [name] => BMW
        )

    [1] => Array
        (
            [model] => S4,
            [model] => X5
        )

    [2] => Array
        (
            [year] => 2010
            [year] => 2011
        )

)

如你所见,它们全部分开,而不是像:

$warehouse['cars'] = array(
 [0] => array(
     'name' => 'Audi',
     'model' => 'S4',
     'year' => '2010'
   )
 ....
)

如何修复/重新分组这种数组输入?

P.S。我知道我可以warehouse[cars][number here][name],但我不愿意。{/ p>

4 个答案:

答案 0 :(得分:1)

我建议你降低数组的复杂性,这样你的代码以后就可以轻松调试了。您可以使用warehouse[cars][][name]cars_names[]等来代替cars_models[]

因此,当您阅读这些值时,您可以使用类似这样的内容

$j=0;
if(count($_POST['cars_names'])) foreach($_POST['cars_names'] as $car){
    $name = $car;
    $model= $_POST['cars_models'][$j];
    ...
    $j++;
}

答案 1 :(得分:0)

不要让PHP为您挑选数组键,而是明确指定它们:

Car 1
<input name="warehouse[cars][1][name]" />
<input name="warehouse[cars][1][model]" />

Car 2
<input name="warehouse[cars][2][name]" />
<input name="warehouse[cars][2][model]" />

答案 2 :(得分:0)

你可能想尝试这样的事情:

$cars = array(
  'car1', 
  'car2'
);

foreach($cars as $key => $car) {
  echo $car;
  echo '<input name="warehouse[cars]['.$key.'][name]" />';
  echo '<input name="warehouse[cars]['.$key.'][model]" />';
  echo '<input name="warehouse[cars]['.$key.'][year]" />';
}

答案 3 :(得分:0)

您可以遍历列表并重新组合条目:

foreach ($_INPUT["warehouse"]["cars"] as $cars) {

    list($key, $value) = each($cars);
    $block[$key] = $value;

    if ($key == "year") {
        $result_list[] = $block;
        $block = array();
    }
}

这要求所有条目都存在year