On Sat, 29 Mar 2014 13:49:37 -0700, 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
If you're trying to find the rate for the input animal and colour values,
you're going to have to walk through all the members of rates, comparing
their animal and colour elements with the input values:
foreach ( $rates as $key => $value ) {
if ( $value["animal"] == $input_animal && $value["color"] == "$input_color
) {
break;
} }
echo "key into rates is: {$key}\n";
echo "rate = {$rates[$key]["rate"]}\n";
echo "rate also = {$value["rate"]}\n";
An alternative data structure might be:
$rates = array(
0=>array(0=>5,1=>10,2=>15),
1=>array(0=>20,1=>25,2=>30),
2=>array(0=>35,1=>40,2=>45),
3=>array(0=>50,1=>55,2=>60)
);
echo "rate = = {$rates[$input_animal][$input_color]}\n";
But whether that is better or not that will depend on what you're
actually trying to do.
--
Denis McMahon, denismfmcmahon(at)gmail(dot)com
|