Re: Need help accessing the key array. [message #185427 is a reply to message #185412] |
Mon, 31 March 2014 02:41 |
Norman Peelman
Messages: 126 Registered: September 2010
Karma:
|
Senior Member |
|
|
On 03/29/2014 04:49 PM, Kongthap Thammachat wrote:
> <?php
>
> $rates = array(
> array("animal" => 0, "color" => 0, "rate" => 5),
> array("animal" => 0, "color" => 1, "rate" => 10),
> array("animal" => 0, "color" => 2, "rate" => 15),
> array("animal" => 1, "color" => 0, "rate" => 20),
> array("animal" => 1, "color" => 1, "rate" => 25),
> array("animal" => 1, "color" => 2, "rate" => 30),
> array("animal" => 2, "color" => 0, "rate" => 35),
> array("animal" => 2, "color" => 1, "rate" => 40),
> array("animal" => 2, "color" => 2, "rate" => 45),
> array("animal" => 3, "color" => 0, "rate" => 50),
> array("animal" => 3, "color" => 1, "rate" => 55),
> array("animal" => 3, "color" => 2, "rate" => 60)
> );
>
> $input_animal = 1;
> $input_color = 2;
>
> ?>
>
> How to access the $rates array to echo the associated rate of "animal" => 1 and "color" => 2 ? (which is 30), should i re-designed the $rates array?
>
> Thanks
>
As another poster has said, a 2D array will work. "animal" and
"color" are unnecessary as key names since they just need to be passed
as indexes into the $rates array:
$rates[0][0] = 5;
$rates[0][1] = 10;
$rates[0][2] = 15;
$rates[1][0] = 20;
$rates[1][1] = 25;
$rates[1][2] = 30;
$input_animal = 1;
$input_color = 2;
echo $rates[$input_animal][$input_color]; // = 30
or
$rates["Dog"][0] = 5;
$rates["Dog"][1] = 10;
$rates["Dog"][2] = 15;
$rates["Cat"][0] = 20;
$rates["Cat"][1] = 25;
$rates["Cat"][2] = 30;
$input_animal = "Cat";
$input_color = 1;
echo $rates[$input_animal][$input_color]; // = 25
or
$rates["Dog"]["Black"] = 5;
$rates["Dog"]["White"] = 10;
$rates["Dog"]["Brown"] = 15;
$rates["Cat"]["Black"] = 20;
$rates["Cat"]["White"] = 25;
$rates["Cat"]["Orange"] = 30;
$input_animal = "Dog";
$input_color = "Brown";
echo $rates[$input_animal][$input_color]; // = 15
--
Norman
Registered Linux user #461062
-Have you been to www.php.net yet?-
|
|
|