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.
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
First of all this is an impossible array. Because in an array the array key must be unique, so you wont be able to have two values for serverA
you have
[serverA] => Array (
[0] => port1,
[1] => user1,
[2] => ip1
),
[serverA] => Array (
[0] => port1,
[1] => user4,
[2] => ip4
),
[serverA] => Array (
[0] => port2,
[1] => user7,
[2] => ip7
),
Please check the array and re-phrase the question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With