Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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:

$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.

like image 500
CodeOverload Avatar asked Jun 20 '26 03:06

CodeOverload


1 Answers

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++;
}
like image 69
adrian7 Avatar answered Jun 21 '26 16:06

adrian7