如何在选择其余数组对象时输出数组对象?

时间:2017-03-26 06:22:39

标签: php arrays

以我的代码为例,如果选择了TYPE,COLOR和SIZE,我想知道如何输出PRIZE。 (例如)$type='apple', $color='green', $size='medium',OUTPUT是14.谢谢!

$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 个答案:

答案 0 :(得分:2)

使用array_filter过滤数组。

$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);

答案 1 :(得分: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'];
         }
    }
}