php - How to properly re-order POST array coming from HTML?

833

Considering I have an array like this:

array:3 [▼
  "description" => array:2 [▼
    0 => "serv1"
    1 => "serv2"
  ]
  "quantity" => array:2 [▼
    0 => "1"
    1 => "2"
  ]
  "cost" => array:2 [▼
    0 => "100"
    1 => "200"
  ]
]

Coming from a HTML form that looks like this:

<div >
  <div >
    <input 
      type="text" 
      name="service[description][]" 
       
    />
  </div>
</div>
<div >
  <div >
    <input 
      type="text" 
      name="service[quantity][]" 
      
    />
  </div>
</div>
<div >
  <div >
    <input 
      type="text" 
      name="service[cost][]" 
       
    />
  </div>
</div>

How can I fix the array in such a way that the result is like this:

[
    ["description" => "serv1", "quantity" => "1", "cost" => "100"],
    ["description" => "serv2", "quantity" => "2", "cost" => "200"],
]
408

Answer

Solution:

Loop the arrays first subarray and use array_column.
Use array_combine and array_keys to get the keys correct.

foreach($_POST["description"] as $key => $val){
    $new[] = array_combine(array_keys($_POST),array_column($_POST, $key));
}
474

Answer

Solution:

If it is an option - rebuild your markup to:

<div >
  <div >
    <input 
      type="text" 
      name="service[0][description]" 
       
    />
  </div>
</div>
<div >
  <div >
    <input 
      type="text" 
      name="service[0][quantity]" 
      
    />
  </div>
</div>
<div >
  <div >
    <input 
      type="text" 
      name="service[0][cost]" 
       
    />
  </div>
</div>

Notice explicit index inname attribute.

With this naming ofinputs your POST array will be already structured as you need and no server side rebuilding is required.

People are also looking for solutions to the problem: PHP get first number

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.