[英]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. 我在php的主题中有一个关联数组,第二个值是1或0。
eg: ([maths] => 1, [science] => 0, [english] => 1)
例如:
([maths] => 1, [science] => 0, [english] => 1)
How can i create a new array of items that have a value of 1? 如何创建一个值为1的新项目数组? ie (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()
. 这应该可以解决问题(但需要PHP 5.3)-请参见
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. 如果可以保证值只能是1或0,则可以执行array_diff()来拾取每个不为 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: 或相应的array_intersect()方法以匹配每个为 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. 如果希望原始键成为新数组中的值,则只需将表达式包装在array_keys()函数中。 eg
例如
$newArray2 = array_keys(array_intersect($array, array(1)));
$array2 = array()
foreach ( $array as $key=>$val ){
if($val == 1)
{
$array2[] = $key;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.