PHP Multidimensional Arrays Tip

I hope this will help someone someday for it took me a minute to figure out.  I am working on a web application that requires the addition of datasets that can be unique or similar.  Each set is to be displayed on a unique row and each row will display data that is being pulled from a DB, a grid framework per se.  Users of the system will be able to alter the contents of the rows and rearrange the order of the rows on the fly before they can save them back to the DB.

I stored everything in multidimensional arrays and when adding new sets or new rows with keys that already exist in the sequence hindered the correct reordering of them.  Example:

The grid is comprised of

$set1[$key1][1]= $array1;

$set2[$key2][1] = $array2;

with $key1 and $key2 being numerical.

Adding a new row of $set1[$key1] at the end of the grid, i.e.,

$set1[$Key1][2] needed to generate the following order:

$set1[$key1][1]= $array1;

$set2[$key2][1] = $array2;

$set1[$Key1][2] = $array1;

However, no matter what I did to populate the arrays sequentially, the order reverted to:

$set1[$key1][1]= $array1;

$set1[$Key1][2] = $array1;

$set2[$key2][1] = $array2;

The easiest fix I could find (I know several others are out there) to achieve the goal was change the keys from numerical to strings.  I did that by combining them and separating them by a glue character (-, @, _, etc.).  The result was:

$set1[$key1_1]= $array1;

$set2[$key2_1] = $array2;

$set1[$Key1_2] = $array1;

To process the data afterward, I split the keys into an array by taking into the account the glue character that I used.

One thought on “PHP Multidimensional Arrays Tip

Comments are closed.