unitedworx
4 years ago
569
4
General

Any better way to transform this html input array?

Posted 4 years ago by unitedworx

i have the below html code which gets duplicated when users click "add" so they can add many offers to an item. (it has a lot more fields but keeping simple here) the returned array i get back is not easy to work with and i prefer it to be structured a bit differently as shown below.

i know i can do something like offers_to_add[0][title] to achieve this but this will be very ugly since i will need to update the array index each time i duplicate it via javascript which i dont think is a good idea.

What i have done is written some code to transform my array in php exactly like I want it but I am not sure if there is a simpler/cleaner way! anyone else came across this hurdle? any cleaner way to do this?

<div class="offer">
    <input type="text" name="offers_to_add[title][]"  >
    <input type="text" name="offers_to_add[text][]"  >
    <input type="text" name="offers_to_add[amount][]"  >
</div>
<!-- add more btn - duplicates the above offer div  -->

returned offers_to_add array has this form

array:3 [
  "title" => array:2 [
    0 => "this is a test 1"
    1 => "this is another test 2"
  ]
  "text" => array:2 [
    0 => "title 1"
    1 => "title 2"
  ]
  "amount" => array:2 [
    0 => ""
    1 => ""
  ]
]

i need it to be

array:2 [
  0 => array:3 [
    "title" => "title 1"
    "text" => "this is a test 1"
    "amount" => ""
  ]
  1 => array:3 [
    "title" => "title 1"
    "text" => "this is a test 1"
    "amount" => ""
  ]
]

this block of code does the job to transform the array. but yet still feels a bit hacky! any cleaner better way of getting the array the way i need it?

       $transformed_data = array();
       $keys = array_keys($offers_to_add);
       foreach ( head($offers_to_add) as $index => $value) {
           foreach ( $keys as $i => $key_name) {
            $transformed_data[$index][$key_name] = array_get($offers_to_add,$key_name.'.'.$index); 
           }
        }

Please sign in or create an account to participate in this conversation.