On 29/03/14 23:32, Kongthap Thammachat wrote:
First a couple of tips:
1. Don't top post, if you reply to something someone else has written,
then type that after the question.
2. If you don't replay to a part of the previous message, delete it, for
example mail footers.
4. Try to use less than 80 character long lines, makes things more
readable for others.
3. Use a proper nntp service, which don't add extra line breaks to messages.
> Hi, what I am trying to do is to receive animal variable and color variable from the user, and finally display associated rate
> for the input animal and input.
> I'm looking for any ways rather than looping through the $rates array, is there any possible ways?
You could use array_filter()
http://www.php.net/manual/en/function.array-filter.php
<?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;
function findRate($array) {
global $input_animal, $input_color;
return $array['animal'] == $input_animal && $array['color'] ==
$input_color;
}
print_r(array_filter($rates, "findRate"));
?>
This will work like if you had looped trough the array, and you will
check each cell in the array (if you are looking for the first
occurrence and using a normal loop, you can always break the loop and
those you do not have to loop trough the whole array.
Maybe you should rethink how to setup the array, having something like
$rates = array(
0 => array( 0 => 5),
0 => array( 1 => 10),
...
3 => array( 2 => 60)
);
this way you have to check that there is a cell in the multi dimensional
array and then take out the value as $rates[1][2]
--
//Aho
|