The form with fields like
<input name="products[][title]">
<input name="products[][description]">
...
<input name="products[][title]">
<input name="products[][description]">
will send post data for "product" in this format:
Array
(
[0] => Array
(
[title] => name1
)
[1] => Array
(
[description] => desc1
)
[2] => Array
(
[title] => name2
)
[3] => Array
(
[description] => desc2
)
)
To make it look like this:
Array
(
[0] => Array
(
[title] => name1
[description] => desc1
)
[1] => Array
(
[title] => name2
[description] => desc2
)
)
You need to add indexes in the form fields:
<form method="POST" ...>
...
<input name="products[0][title]">
<input name="products[0][description]">
...
<input name="products[1][title]">
<input name="products[1][description]">
...
<input type="submit">
</form>
In this second form, there is different ways to format an array. For example:
if you want a different format using only subset of keys, you can use the php native function array_map( $callback , $source )
$result= array_map(function($item){
return ["title"=>$item["title"]];
}, $products);
print_r($result);
Will result in:
$result=[
[
"title"=>"name1"
],
[
"title"=>"name2"
],
[
"title"=>"name3"
],
];
In the "Laravel" way, you can do it with collections:
$collection = collect($products);
$newCollection = $collection->map(function ($item, $key) {
return [ "title" => $item["title"] ];
});
$result= $newCollection->all();
And the result will be the same
There is no common way to deal with an array with ungrouped columns like the first example. But if you want to convert from the original array without changing the HTML code (without adding indexes), you can do it:
$result=[];
foreach($products as $index=>$product){
foreach($product as $key=>$value){
$result[$index/2][$key]=$value;
}
}
print_r($result);
And also, if you want only some keys (title, for example):
$result=[];
foreach($products as $index=>$product){
$result[$index/2]["title"]=$product["title"];
}
print_r($result);