开发者

how to verify order of elements in a list or array

ETA: I'm thinking that my question needs some clarification. I don't want to sort my arrays. I want to be sure that a given array that is in order by a particular criterion, is also in order by another criterion. I made a graphic to illustrate. Each开发者_StackOverflow row is an array ordered by number. If the letters are also in order, the array passes the test.

how to verify order of elements in a list or array


Original Question

I have a parent class PhysicalCount with 2 properties: date, count. I also have subclasses of PhysicalCount: ClutchCount, FryCount and MatCount. When I have a mixed array of PhysicalCounts and subclasses I need to verify (not set!) that the order matches these criteria:

  1. objects are in order by date
  2. 0 to 1 objects of each child class may exist
  3. 0 to many objects of PhysicalCount may exist
  4. if a ClutchCount is present it must have an earlier date than a FryCount or MatCount if those exist
  5. if a FryCount is present it must have an earlier date than a MatCount if that exists

Boiled down, the question is something like:

Given a list sorted by one criterion ($o->date in my case), what is the most efficient way to ascertain that sorting that same list by another criterion (get_class($o)in my case) will result in the same order?

I'd prefer a solution in PHP, but I'm thinking this is a fairly common problem that has a standard solution that I just don't know the name of. (Here is me regretting my degree choice [not CS]).


Based on our discussion in the comments, what you need is a sort that is somewhat "stable" (not actually a stable sort by definition though) use usort to sort the objects in the array in a user-defined way. You can specify in your $cmp_function the criteria you mentioned in your question, so that the sorted array fits your needs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜