Search code examples
phparraysmultidimensional-arraygrouping

Output a multidimensional array in groups


I have an multidimensional array of data which represents the list of users that are connected to our servers. Each array contains information about a connection. The same user could be connected to any number of ports on different servers.

Array(  [0] => Array(
            [0] => serverA
            [1] => port1,
            [2] => user1,
            [3] => ip1
        ),
        [1] => Array(
            [0] => serverB
            [1] => port2,
            [2] => user2,
            [3] => ip2
            ),
        [2] => Array(
            [0] => serverC
            [1] => port1,
            [2] => user3,
            [3] => ip3
            ),  
        [3] => Array(
            [0] => serverA
            [1] => port1,
            [2] => user4,
            [3] => ip4
            ),  
        [4] => Array(
            [0] => serverB
            [1] => port4,
            [2] => user5,
            [3] => ip5
            ),  
        [5] => Array(
            [0] => serverC
            [1] => port1,
            [2] => user6,
            [3] => ip6
            ),
        [6] => Array(
            [0] => serverA
            [1] => port2,
            [2] => user7,
            [3] => ip7
            ),              
)

I need to group by first the servers and then the ports and print out a list showing the connected users for each server and port as below:

ServerA
    port1
        user1,ip1
        user4,ip4
    port2
        user7,ip2
ServerB
    port2
        user2,ip2
    port4
        user5,ip5
ServerC
    port1
        user3,ip3
        user6,ip6

I'm confused as to how to approach this. Should I be using a multidimensional array sort function (e.g. array_multisort) or should I be building a new array? An examples would be greatly appreciated.


Solution

  • You can create a new array where you summarize the data and then print it in the required format:

    $newArr = array();
    
    foreach($arr as $k => $v) {
            if(!isset($newArr[$v[0]][$v[1]])) {
                    $newArr[$v[0]][$v[1]] = array();
            }
            $newArr[$v[0]][$v[1]][] = array($v[2],$v[3]);
    }
    
    foreach($newArr as $k => $v) {
            echo $k,"\n";
            foreach($v as $k1 => $v1) {
                    echo "\t$k1\n";
                    foreach($v1 as $k2 => $v2) {
                            echo "\t\t", $v2[0],",",$v2[1],"\n";
                    }
            }
    
            echo "\n";
    }
    

    See it