Reputation: 3
I am currently looking a rewriting some perl cgi scripts into php, mainly in order so I can learn php. Everything is going well, except I can't get my head round how to convert a perl hash of hash of hash into a php array. Take this scenario (not real, but the idea is the same) I have 5 network nodes called A,B,C,D,E. Each node is actually a stack of 3 switches called TOP, MIDDLE, BOTTOM Each switch has 10 interfaces called 1 to 10.
I have a script that polls round every interface and record the input bytes in a database like this:-
node switch interface bytes
A TOP 1 999
B MIDDLE 1 999
A MIDDLE 2 999
etc
I can read the database in php, but then I come unstuck. In perl I just read the data and store it in a hash of hashes by looping though the query of the database
`While $ref fetchrow_hashref() {
$hash{$ref{'NODE'}}{$ref{'Switch'}}{$ref{'Interface'}=$ref{'Bytes'}
}`
So now I can access any value in my cgi code using the names
$hash{A}{Top}{1}
would return 999
But when I try and do something similar in php with associative array of arrays, it go wrong. I've used
$hash[]=[$ref["NODE"}=>
[$ref["Switch"]=>
[$ref["Interface"]=>
$ref["Bytes"]
]
]
];
A var_dump of the hash looks correct, but I don't appear to be able to print a value out of the array using
print $hash[A][TOP][1];
Please can I have pointers to my mistakes
Upvotes: 0
Views: 232
Reputation: 96159
That would be
while( $ref=somefetchingfunction_or_method() ) {
$hash[$ref['NODE']][$ref['Switch']][$ref['Interface']]=$ref['Bytes'];
(i.e. just replacing all {
by [
, }
by ]
and fixing the missing last ]
.)
edit: sscce:
<?php
$hash = [];
foreach( gen_fetch() as $ref ) {
$hash[$ref['NODE']][$ref['Switch']][$ref['Interface']]=$ref['Bytes'];
}
echo $hash['A']['TOP'][1];
// generator requires php version >= 5.5, see http://php.net/language.generators.overview
function gen_fetch() {
$keys = ['NODE','Switch','Interface','Bytes'];
foreach( [['A','TOP',1,997],['B','MIDDLE',1,998],['A','MIDDLE',2,999]] as $r) {
yield array_combine($keys,$r);
}
}
prints 997
.
Upvotes: 1