I have an array in PHP that is simply strings. These strings represent relationships that can occur between different distances of family. It looks like this:
0 => 'Unknown',
1 => 'Parent',
2 => 'Grandparent',
3 => 'Sibling',
4 => 'Child',
5 => 'Grandchild',
6 => 'Spouse',
7 => 'Self',
9 => 'Step Parent',
10 => 'Step Sibling',
11 => 'Step Child',
etc...
This array works great, but I'm running into a problem where I would like to be able to sort these items in a purely custom way (specifically closer-to-father away starting with Spouse/Sibling ending with most distant relations like X-in-law), but I also would like the list to be added to over time. My initial thought was to simply order them as they needed to be ordered in the array, but that does not allow me to add relations at a later date (though it's doubtful this would ever happen, I'd rather be safe than sorry). The best solution I could come up with (an seemingly a good one in my mind) was to make a simple PHP object that would hold both the name of the relation and an arbitrary "sort" value like this new Relation('Unknown', 0);
. The problem is, it appears that you cannot instantiate objects while making an array with the X => Y
syntax, as I have syntax errors when I try to write this:
0 => new Relation('Unknown', 0),
1 => new Relation('Grandparent', 1),
etc...
Is there a way that this could work or possibly a better solution? It seems at this point I may have to generate the array the first time it is requested (in a getter) using Array pushes then store it, but I'd rather have it nicely formatted. Am I just out of luck?
Edit - To clarify: The keys right now are being used as the stored value in the database. In essence, we are using the array as an enum in other languages.
Use the array as a map, such as relationship_name => relationship_distance. If it is more convenient, you can do relationship_distance => relationship_name. Make the relationship_distance values arbitrary, with gaps in between so that intermediate distances can be added later. For example:
'Sibling' => 1,
'Parent' => 10,
'Grandparent' => 20,
'Greatgrandparent' => 30,
'Uncle' => 13,
'BrotherInLaw' => 17,
Then you can sort the map by they keys or the values and add new entries as needed.