views:

54

answers:

2

I'm trying to figure out how to sort a 2d array into a 3d array in PHP. The array contains tasks from users in a management tree and is currently arranged like so:

Array ( [0] => Array ( [Title] => Test Task [Author] => 5 [DateIn] => 2010-09-15 [Deadline] => 2010-09-30 [Position] => 1 [Description] => This is a test task [Assignee] => 3 ) [1] => Array ( [Title] => Test Task [Author] => 5 [DateIn] => 2010-09-15 [Deadline] => 2010-09-29 [Position] => 1 [Description] => Blah blah [Assignee] => 3 ) ) 

I want to sort it so that it's a 3d array where each 2nd level array contains all of the tasks assigned to one user. Is there an easy way to do this? The closest thing I found was array_multsort, but that doesn't quite do what I want.

*Edits This is basically a task manager app for the company I currently work for. Managers need to be able to see the tasks that have been assigned to their employees. I currently have employees and supervisors organized into a tree, so they need to see everything in their branch.

Right now, the function I've written returns the tasks for employees of each "manager" sorted in no particular order. To reduce clutter, I need to be able to only display one "employee's" tasks at a time. Currently this is not possible, as the structure of the array is such that it simply contains a list of all the tasks where the author is marked as the current user.

In short, I would like to sort these tasks into a 3 dimensional array, where each 2nd level array contains the tasks belonging to one "employee" belonging to the current user.

+2  A: 

I don't quite understand what you're getting at, but if you want to produce a new array which lists tasks by assignee, then you can use the following.

foreach ( $old as $task )
  $new[$task['Assignee']][] = $task;

This will give you an array where the keys are the assignee IDs and the sub arrays are the tasks assigned to them.

jay.lee
+1  A: 

So if I understand, your array will have the following arrangement:

manager1
    employee1
        task1
    employee2
        task2
        task3
manager2
    employee3
.
.
.

Is this correct? If so, then assuming "author" is the manager and "assignee" is the employee, try the following:

$new_array = array();
foreach($old_array as $task){
    if(array_key_exists($task["author"], $new_array)){ // the manager already has an array slot
        if(array_key_exists($task["assignee"], $new_array[$task["author"]])){ // the employee already has an array slot under this manager
            array_push($new_array[$task["author"]][$task["assignee"]], $task);
        } else { // manager exists, employee doesn't
            $new_array[$task["author"]][$task["assignee"]][0] = $task;
        }
    } else { // manager doesn't exist
        $new_array[$task["author"]] = array($task["assignee"] => array($task));
    }
}
steven_desu