如果我的数组结构如下:
[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
我该怎么办?
答案 0 :(得分:2)
您可以使用array_filter功能:
$good_value ="good";
$new_array = array_filter($old_array,function($value)use($good_value){
return $value === $good_value;
});
答案 1 :(得分:0)
您还可以使用利用foreach
和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;
}
}
答案 2 :(得分:0)
你可以使用一个循环
$newArray = array();
foreach($oldArray as $value) {
if($value == 'good')
$newArray[] = $value
}
如果您需要保留密钥
$newArray = array();
foreach($oldArray as $key=>$value) {
if($value == 'good')
$newArray[$key] = $value
}
答案 3 :(得分:0)
使用PHP的array_filter()函数。
function good($var)
{
return($var == "good");
}
$ary = array_filter($ary, "good");
print_r($ary);
如果需要重新索引数组,只需添加:
$ary = array_values($ary);
<强> CodePad example 强>