Skip to content
Advertisement

Group and sort multiple associative arrays in PHP based on two conditions

I have couple of associative arrays like this

JavaScript

I want to get the arrays that have the latest hired year, and also based on the department order.

so the department priorities are ['math', 'science', 'social'] (ordered based on priority)

If only one array has recent years: For example from the above array we only get this one:

JavaScript

since this one is the only one that has most recent hired year, we dont care about the department.

But if there are multiple arrays with same year, then we look at the department.

JavaScript

Since we have arrays with 2010 as hired year, I want to get the ones which are under math department. Since math is first in the department order, if there were no math, we would get the ones with science, if no science then social. We would just get $arrayOne and $arrayThree in this example.

I started by creating a function but I am confused how to check against the year and department

JavaScript

Advertisement

Answer

I have written the following code:

The getResult method first checks if of the most recent year there is one item, if so, it returns this one item. If not it will loop through the array based on the department order and returns the first items that are present.

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement