PHP按值删除关联数组中的元素

时间:2013-01-04 23:11:56

标签: php arrays

  

可能重复:
  Remove integers in array less than X with PHP

$array = array( 
    "a" => 10, 
    "b" => 9, 
    "c" => 8, 
    "d" => 7,
    "e" => 6,
    "f" => 5,
    "g" => 4,
    "h" => 3 
    );

如果值小于6,我如何删除项目?即,我怎样才能获得以下数组?

$array = array( 
    "a" => 10, 
    "b" => 9, 
    "c" => 8, 
    "d" => 7,
    "e" => 6
    );

3 个答案:

答案 0 :(得分:7)

array_filter非常适合:

$new = array_filter($old,function($a) {return $a >= 6;});

答案 1 :(得分:1)

一个简单的迭代就是:

$new_array = array();
foreach($arras as $key => $value){
  if($value >= 6)new_array[$key] = $value;
}

答案 2 :(得分:1)

foreach($array as $index=>$value) {
  if ( $value < 6) {
    unset($array[$index]);
  }
}

foreach($array as $index=>$arr_value) {
  if ( $value >= 6) {
    $new_array[$index] = $arr_value;
  }
}