如果我有一个结构如下的数组:
[0] => bad
[1] => good
[2] => bad
[3] => bad
[4] => good
[5] => bad
[6] => bad
[7] => good
[8] => bad
[9] => bad
[10] => good
[11] => bad
我需要一个只有好的项目的数组,比如:
[0] => good
[1] => good
[2] => good
[3] => good
[4] => good
我能怎么做 ?
你可以使用array_filter函数:
$good_value ="good";
$new_array = array_filter($old_array,function($value)use($good_value){
return $value === $good_value;
});
您还可以使用一种利用foreach
and的方法array_push
:
$goodArray = array();
foreach($array as $value) {
if $value = "good" {
array_push($goodArray, $value);
}
}
或者,如果您想维护原始索引:
$goodArray = array();
foreach($array as $key => $value) {
if ($value = "good") {
$goodArray[$key] = $value;
}
}
你可以只使用一个循环
$newArray = array();
foreach($oldArray as $value) {
if($value == 'good')
$newArray[] = $value
}
是否需要保留密钥
$newArray = array();
foreach($oldArray as $key=>$value) {
if($value == 'good')
$newArray[$key] = $value
}
使用 PHP 的array_filter()函数。
function good($var)
{
return($var == "good");
}
$ary = array_filter($ary, "good");
print_r($ary);
如果您需要重新索引数组,只需添加以下内容:
$ary = array_values($ary);