How to sort multiple arrays of form fields in php?

I have an array from the form view:

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 way to sort it more?

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
        )

)
+4
source share
4 answers

Since you indicated that you can change the form, you can 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 convenient for the loop, since it is isolated from form_key, submitetc ...

+7
source

Select one field to iterate over, then take values ​​from other fields:

foreach($data['sku'] as $key=>$sku){
    $product = $data['product'][$key];
    $related_product = $data['related_product'][$key];
    $qty = $data['qty'][$key];
}

Then you can create a new array or do something with values.

$newArray[] = array(
    'sku' => $sku,
    'product' => $product,
    'related_product' => $related_product,
    'qty' => $qty
);
+3
source

,

$rs = [];
foreach($_POST as $k1=>$elem) {
    if(is_array($elem)) {
        foreach($elem as $k2=>$value) {
            $rs[$k2][$k1] = $value;
        }   
    }
}
+2
    $newArray = [];
    foreach ($array as $mainKey => $value ) {
        foreach($value as $subKey => $subValue) {
            $newArray[$subKey][$mainKey] = $subValue;
        }
    }

    print_r($newArray);
0

Source: https://habr.com/ru/post/1608890/


All Articles