Carlo Carlo - 20 days ago 8
PHP Question

How to group posted array names by index in PHP

I am currently working on a project where the fields scale when clicking on the "Add" button.

I am grouping each field like this:

name="packaging[]"
,
name="packaging[1]"
,
name="packaging[2]"
and so on. When I submit the form, this is how the data looks like when posted:

Array
(
[packaging] => Array
(
[0] => 1
[1] => 2
)

[quantity] => Array
(
[0] => 1
[1] => 2
)

[total-weight] => Array
(
[0] => 1
[1] => 2
)

[length] => Array
(
[0] => 1
[1] => 2
)

)


Using PHP I would like to convert the above code to look like this:

Array
(
[0] => Array
(
[packaging] => 1,
[quantity] => 1,
[total-weight] => 1,
[length] => 1,
)
[1] => Array
(
[packaging] => 2,
[quantity] => 2,
[total-weight] => 2,
[length] => 2,
)
)


Any help would be greatly appreciated.

Answer

Try this....

$array=array();
foreach($data as $key=>$value){
    foreach($value as $k=>$val){
         $array[$k][$key]=$val;
    }
}

DEMO

Comments