How to Save Data into a Multidimensional Array

The other day I ran into a situation where I needed to group form data by field collections into a multidimensional array. For the life of me, I’m not sure if it was the stars or just a case of amnesia, I could not remember how to do it. Fortunately, it came back to me but just for a future reference to myself or to those of you looking, here is how you do it.


Say you have a form like so:

<form action=“submit” id="food_basket">

<div id=“group_1”>

    <input type="text" name="name">

    <input type="text" name="category">

</div>


<div id=“group_2”>

    <input type="text" name="name">

    <input type="text" name="category">

</div>


<div id=“group_3”>

    <input type="text" name="name">

    <input type="text" name="category">

</div>


<input type="submit">

</form>

Ideally we would like our data to be structured like this after submit:

food_basket {

    [0] {

        "name": "Apple",

        "category": "fruit",

    }

    [1] {

        "name": "Potato",

        "category": "vegetable",

    }

    [2] {

        "name": "Papaya",

        "category": "fruit",

    }

}

To convert this into a multidimensional array, we just need to append the input name value by adding brackets in the order array_name[#][array_label] so our form now will look something like this:

<form action=“submit” id="food_basket">

<div id=“group_1”>

    <input type="text" name="food_basket[0][name]">

    <input type="text" name="food_basket[0][category]">

</div>


<div id=“group_2”>

    <input type="text" name="food_basket[1][name]">

    <input type="text" name="food_basket[1][category]">

</div>


<div id=“group_3”>

    <input type="text" name="food_basket[2][name]">

    <input type="text" name="food_basket[2][category]">

</div>


<input type="submit">

</form>

Now when you go and submit the form, your submission for food_basket will be in a multidimensional array, making it easier to work with your submitted data.

Hey, I’m Misha, a web developer from Washington, DC. Hope you enjoyed this article! Feel free to read other posts, view my work, or say hello!