1

With my code as an example below, I'd like to know how to output PRIZE if TYPE, COLOR and SIZE is selected. (e.g.) $type='apple', $color='green', $size='medium' and the OUTPUT is 14. Thanks!

$fruits = [

    ['type' => apple, 'color' => 'green' , 'size' => 'small' , 'prize' => 10],

    ['type' => apple, 'color' => 'red' , 'size' => 'medium' , 'prize' => 12],

    ['type' => apple, 'color' => 'green' , 'size' => 'medium' , 'prize' => 14]

];

2 Answers 2

2

Use array_filter to filter the array.

$result = array_filter($fruits, function($v) use ($selected){
    return ($v['type'] == $selected['type']) && ($v['color'] == $selected['color']) && ($v['size'] == $selected['size']) ? true : false;
});
print_r($result);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Kris! I will be using this on Wordpress and return the result asynchronously on a Form. By the way, I will be loading up about 40 rows of TYPE, COLOR, SIZE and PRICE. Any advice on how I could put all of those on my array? Sorry still a newbie :)
1
function getFruitPrice($type, $color, $size) {
    for(int $i = 0; $i < count($fruits); $i++) {
      if($fruits[$i]['type'] == $type &&
         $fruits[$i]['color'] == $color &&
         $fruits[$i]['size'] == $size) {
             return $fruits[$i]['price'];
         }
    }
}

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.