开发者

Fix multi-dimensional foo[a][][b] array inputs

I'm using multi-dimensional input tags in my 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]" />

The issue with that is that i'm getting some messed up array in the PHP side:

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

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

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

)

As you see it's all separated instead of something like开发者_如何学JAVA:

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

How to fix/re-group this kind of array inputs?

P.S. i know i can do warehouse[cars][number here][name] but i prefer not to.


I suggest you reduce the complexity of the arrays, so your code will be easy to debug later. Instead of warehouse[cars][][name] and such you can use cars_names[], cars_models[] and so on.

So when you read the values you can use smthing like this

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


Instead of letting PHP pick out the array keys for you, just specify them explicitly:

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]" />


You might want to try something like this:

$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]" />';
}


You can iterate over the list and regroup the entries:

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

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

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

That requires that year is really present for all entries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜