1

i have an array that i get from a form with alot of fields, i need to order those fields under an array and that array under the ''main'' array. Ill post what i have, and what i need to get. WHAT I HAVE:

Array
(
    [perfil_area1] => Array
    (
        [0] => a2
        [1] => a3
    )

    [perfil_years] => Array
    (
        [0] => 2
        [1] => 4
    )

    [perfil_function] => Array
    (
        [0] => f1
        [1] => f4
    )

    [perfil_obs] => Array
    (
        [0] => teste1
        [1] => teste2
    )

    [perfil_company] => Array
    (
        [0] => emp1
        [1] => emp2
    )
)

This is what i need to be so i can turn it into a query: What i need

Array
(
    [0] => 
    (
        [perfil_area1] => a2
        [perfil_years] =>  2
        [perfil_function] =>  f1
        [perfil_obs] =>  teste1
        [perfil_company] =>  emp1
    )
    [1] =>
    (
        [perfil_area1] => emp2
        [perfil_years] =>  2
        [perfil_function] =>  f4
        [perfil_obs] =>  4
        [perfil_company] =>  a3
    )
)

i have tried with 2 foreach but i didnt manage to get it done. I have read Create a multidimensional array in a loop , how to create multidimensional array using a foreach loop in php? , create multidimensional array using a foreach loop , Converting an array from one to multi-dimensional based on parent ID values and some more but i still cant do it. Any tips on how to create it?

BRABO
  • 100
  • 7
  • 1
    Have you read how to "transpose" an array? – mickmackusa Aug 27 '21 at 13:13
  • And https://stackoverflow.com/q/62612089/2943403 (no upvotes on that duplicate). – mickmackusa Aug 27 '21 at 13:21
  • Save yourself a lot of hassle and modify your form to suit your process. https://stackoverflow.com/a/17799565/2943403 – mickmackusa Aug 27 '21 at 13:24
  • i can modify it but will take me longer because it has fields added dynamically and i will have to change the js behind it. This way i can just convert the arrays to one array. Thanks anyway – BRABO Aug 27 '21 at 13:34

2 Answers2

1

You just need to loop over the input array and build the new array

$new = [];
foreach ($in as $key=>$arr) {
    $new[0][$key] = $arr[0];
    $new[1][$key] = $arr[1];
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
1
<?php

$result = [];

for ($i=0; $i<count(reset($array)); $i++) {
    $result[] = array_combine(array_keys($array), array_column($array, $i));
}

Please read the manual for more details about array_combine(), array_keys() and array_column().

spinsch
  • 1,415
  • 11
  • 23