Search an array and create an array from the results
I have an associated array in php of subjects with either 1 or 0 as the second value.
e.g: ([maths] => 1, [science] => 0, [english] => 1)
How can i create a new array of items that have a value o开发者_如何转开发f 1? i.e. (maths, english)
Thanks
$output = array_filter($input, function($v) {
return $v == 1;
});
This should do the trick (but requires PHP 5.3) - see array_filter()
.
$results = array();
foreach($array as $k=>$v){
if($v == 1){
$results[] = $k;
}
}
If you can guarantee that values will only ever be 1 or 0, then you can do an array_diff() to pick up every value that isn't 0.
$array = array( 'maths' => 1,
'science' => 0,
'english' => 1);
$newArray = array_diff($array, array(0));
var_dump($newArray);
EDIT
or the corresponding array_intersect() method to match every value that is a 1:
$newArray2 = array_intersect($array, array(1));
var_dump($newArray2);
If you want the original keys to become the values in your new array, then just wrap the expression in an array_keys() function. e.g.
$newArray2 = array_keys(array_intersect($array, array(1)));
$array2 = array()
foreach ( $array as $key=>$val ){
if($val == 1)
{
$array2[] = $key;
}
}
精彩评论