如何根据2个值过滤数组

时间:2012-02-22 11:55:57

标签: php arrays multidimensional-array filtering

我有一个包含多个行集的数组,包括类型,标题和描述....我需要过滤数组并仅显示基于type =“education”和type =“experience”的那些行集。

foreach () { if (type = 'experience') ..do something / else ... do something else}

2 个答案:

答案 0 :(得分:3)

使用array_filter

function myfilter($row){
    return ($row['type']=='experience'|| $row['type']=='education'); 
}
$result = array_filter($input_array, 'myfilter');

array_filter函数保留原始数组的键。如果您不想要此行为,请使用array_values

$result = array_values(array_filter($input_array, 'myfilter'));

答案 1 :(得分:0)

$array = array(array('type'=>'experience','title'=>'xyz','des'=>'dfasdasdasdas'),
        array('type'=>'education','title'=>'xddfdfyz','des'=>'dfasdasdasdas'),
    array('type'=>'dsad','title'=>'afdf','des'=>'dfasdasdasdas'),
    array('type'=>'education','title'=>'gfdsfr','des'=>'dfasdasdasdas'));

foreach($array as $value){
    if($value['type'] == 'experience'){
        //do your stuff
    }else if ($value['type'] == 'education'){
        //do your stuff
    }else{
        //do your stuff
    }
}

假设您的数组结构如图所示,如果条件为

,则可以更改foreach循环
 if($value['type'] == 'experience' || $value['type'] == 'education'){
//do your stuff
}else{
//do your stuff
}