Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort multiple form field arrays in php?

I have an array from a form submission:

Array
(
    [form_key] => 9juTLit5qQbaBb98
    [sku] => Array
        (
            [0] => AC25
            [1] => AC30
            [2] => AC31
        )

    [product] => Array
        (
            [0] => 95
            [1] => 100
            [2] => 101
        )

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

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

)

Is there a good way to sort it more like?

Array
(
    [form_key] => 9juTLit5qQbaBb98
    [0] => Array
        (
            [sku] => AC25
            [product] => 95
            [qty] => 2
        )

    [1] => Array
        (
            [sku] => AC30
            [product] => 100
            [qty] => 2
        )


    [2] => Array
        (
            [sku] => AC31
            [product] => 101
            [qty] => 2
        )

)
like image 257
Sean Kimball Avatar asked Dec 14 '22 11:12

Sean Kimball


1 Answers

Since you indicated that you may be able to change the form, you could do something like this and get the desired array structure:

<input type="text" name="data[0][sku]">
<input type="text" name="data[0][product]">
<input type="text" name="data[0][qty]">

<input type="text" name="data[1][sku]">
<input type="text" name="data[1][product]">
<input type="text" name="data[1][qty]">

The array will be in $_POST['data'] which is handy for looping since it is isolated from form_key, submit etc...

like image 153
AbraCadaver Avatar answered Dec 25 '22 09:12

AbraCadaver