Carlo Carlo - 23 days ago 5
PHP Question

How to group array keys 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 code:

  $rows = 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)

 );
  $res_array = array();
  $total_records = count($rows['packaging']);
 for($i=0;$i<$total_records;$i++)
 {
     $res_array[] = array('packaging'=>$rows['packaging']   [$i],'quantity'=>$rows['quantity'][$i],
    'total-weight'=>$rows['total-weight'][$i],'length'=>$rows['length'] [$i]);
 }
print_r($res_array);