numediaweb
numediaweb

Reputation: 17010

Group serialized JS array into similar objects/arrays based on their ID

I have a complex form with multidimensional input fields;

<input type="hidden" name="product[12267][ID]" value="76">
<input type="radio" name="product[12267][electrical_support]" value="1">
<input type="radio" name="product[12267][electrical_support]" value="0" checked="">
<input type="checkbox" name="product[12267][drinks]" value="1" >
<input type="radio" name="product[9999][electrical_support]" value="1">
<input type="hidden" name="product[9999][ID]" value="58">

The form is sent to php using jquery's ajax and serializeArray;

var formData = new FormData();
formData.append('action', 'add_to_cart');
formData.append('products', $(form).serializeArray());

This outputs an array of objects in the console like :

0: Object
     name: "product[12267][starting_price]"
     value: "15"
1: Object
     name: "product[12267][ID]"
     value: "79"
...

My question is how can I group/arrange this multiple objects (either preior in js or later in php) into single product arrays based on the ID, something like;

$products[12267] = array('starting_price' => 15, 'ID' => 79);

Hope I explained well the case, please let me know if I need to provide further details

Upvotes: 1

Views: 428

Answers (2)

numediaweb
numediaweb

Reputation: 17010

After some try/error I found that I don't need to use serializeArray() in the js, as this kills the associative array in the form input fields! The solution is to listen to the form submit event and pass it inside FormData like;

var formData = new FormData(event.target);

then in PHP, use something like;

$products = isset($_POST['product']) ? $_POST['product'] : false;

The products keep the form input fields array intact.

Upvotes: 1

cpopolo
cpopolo

Reputation: 53

Unless I'm missing something, this should work assuming $inproducts is from $_POST['product'] and contains a ragged array of product info.

$products = array();    
foreach ($inproducts as $key=>$inproductarray) {
        if (!isset($products[$key])) {
            $products[$key]=array();
        }
        foreach ($inproductarray as $subkey=>$subvalue) {
            $products[$key][$subkey] = $subvalue;
        }
    }

Note that the resulting array could still be ragged. If a form field is not found in the POST array, it won't be added to the result array. If you need to insure that all products have all properties, name the keys when you create the array for the product:

$products[$key]=array('id'=>$key,'starting_price'=null,'electrical_support='null',etc).

They'll be filled in as you iterate the $inproductarray.

Upvotes: 2

Related Questions