2

Trying to convert a perl script to php.

In perl I have a hash like this

my %SPEC=(
odmiles           => ['OD Miles','Mileage','odmiles:ecmmiles','num'],
ecmmiles          => ['ECM Miles',0,'','num',' ECM'],
cdl               => ['CDL','CDL']);

I can access the data like so:

$SPEC{ecm}[3]  # output = num

Since a hash in perl does not run in order I'll do a simple array

@ORD=('odmiles','ecmmiles','cdl');

then loop

foreach my $S (@ORD) {
  print $S." = ".$SPEC{$S}[0]."<br />";
  }

I can do similar with php but having issue accessing elements past [0] in my hash.

5
  • My canonical response to "translate from X to Y": hyperpolyglot.org/scripting; nothing special about this link, there are probably several comparison tables like this Commented Jun 8, 2012 at 17:19
  • I am not asking to have my code translated. I am asking how to access the elements past the first in my hash using php. i.e. Mileage, position[1] in above example Commented Jun 8, 2012 at 17:24
  • Here's what I have $array = array("odmiles" => "OD Miles"); $array["odmiles"]; Commented Jun 8, 2012 at 17:25
  • @chrisrth Or perhaps $SPEC = array("odmiles" => array("OD Miles", "Mileage", ...)); Not sure if that is valid PHP. Commented Jun 8, 2012 at 17:26
  • @chrisrth I am not sure I am understanding you correctly.. you know that $SPEC{$S}[0] gives the first element, and you don't know that $SPEC{$S}[1] gives the second, and so forth? Commented Jun 8, 2012 at 17:28

1 Answer 1

3

I think you're looking for this:

$SPEC = array(
  'odmiles'           => array('OD Miles','Mileage','odmiles:ecmmiles','num'),
  'ecmmiles'          => array('ECM Miles',0,'','num',' ECM'),
  'cdl'               => array('CDL','CDL')
);

Accessing elements would then work something like this:

echo $SPEC['odmiles'][0]; // 'OD Miles'
echo $SPEC['odmiles'][1]; // 'Mileage'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.