dpgjci27392 2012-07-10 02:40
浏览 13
已采纳

不自然的PHP数组

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.

  • 写回答

2条回答 默认 最新

  • drxt70655 2012-07-10 03:08
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图