根据值从多维数组中删除元素

时间:2010-12-16 22:52:10

标签: php arrays multidimensional-array

我正在尝试根据值从多维数组中删除元素。在这种情况下,如果子数组的键'year'具有值2011,我希望该子数组出来。

仅供记录:我正在运行PHP 5.2。

我的数组看起来像这样:

Array
(
    [0] => Array
        (
            [filmId] => 61359
            [url] => http://www.moviemeter.nl/film/61359
            [title] => Unstoppable
            [alternative_title] => 
            [year] => 2011
            [thumbnail] => http://www.moviemeter.nl/images/covers/thumbs/61000/61359.jpg
            [average] => 0
            [votes_count] => 0
            [similarity] => 100.00
            [directors_text] => geregisseerd door Richard Harrison
            [actors_text] => met Chen Shilony, Ruben Crow en David Powell
            [genres_text] => Drama / Komedie
            [duration] => 90
        )
    [1] => Array
        (
            [filmId] => 87923
            [url] => http://www.moviemeter.nl/film/87923
            [title] => Unstoppable
            [alternative_title] => 
            [year] => 2011
            [thumbnail] => http://www.moviemeter.nl/images/covers/thumbs/87000/87923.jpg
            [average] => 0
            [votes_count] => 0
            [similarity] => 100.00
            [directors_text] => geregisseerd door Example Director
            [actors_text] => met Actor 1, Actor 2 en Actor 3
            [genres_text] => Drama / Komedie
            [duration] => 90
        )
    [2] => Array
        (
            [filmId] => 68593
            [url] => http://www.moviemeter.nl/film/68593
            [title] => Unstoppable
            [alternative_title] => 
            [year] => 2010
            [thumbnail] => http://www.moviemeter.nl/images/covers/thumbs/68000/68593.jpg
            [average] => 3.3
            [votes_count] => 191
            [similarity] => 100.00
            [directors_text] => geregisseerd door Tony Scott
            [actors_text] => met Denzel Washington, Chris Pine en Rosario Dawson
            [genres_text] => Actie / Thriller
            [duration] => 98
        )
    [3] => Array
        (
            [filmId] => 17931
            [url] => http://www.moviemeter.nl/film/17931
            [title] => Unstoppable
            [alternative_title] => Nine Lives
            [year] => 2004
            [thumbnail] => http://www.moviemeter.nl/images/covers/thumbs/17000/17931.jpg
            [average] => 2.64
            [votes_count] => 237
            [similarity] => 100.00
            [directors_text] => geregisseerd door David Carson
            [actors_text] => met Wesley Snipes, Jacqueline Obradors en Mark Sheppard
            [genres_text] => Actie / Thriller
            [duration] => 96
        )
)

8 个答案:

答案 0 :(得分:72)

试试这个:

function removeElementWithValue($array, $key, $value){
     foreach($array as $subKey => $subArray){
          if($subArray[$key] == $value){
               unset($array[$subKey]);
          }
     }
     return $array;
}

然后你会这样称呼:

$array = removeElementWithValue($array, "year", 2011);

答案 1 :(得分:9)

试试这个:

function remove_element_by_value($arr, $val) {
   $return = array(); 
   foreach($arr as $k => $v) {
      if(is_array($v)) {
         $return[$k] = remove_element_by_value($v, $val); //recursion
         continue;
      }
      if($v == $val) continue;
      $return[$k] = $v;
   }
   return $return;
}

答案 2 :(得分:4)

$array[] = array('year' => 2010, "genres_text" => "Drama / Komedie");
$array[] = array('year' => 2011, "genres_text" => "Actie / Thriller");
$array[] = array('year' => "2010", "genres_text" => "Drama / Komedie");
$array[] = array('year' => 2011, "genres_text" => "Romance");

print_r(remove_elm($array, "year", 2010)); // removes the first sub-array only
print_r(remove_elm($array, "year", 201)); // will not remove anything
print_r(remove_elm($array, "genres_text", "drama", TRUE)); // removes all Drama
print_r(remove_elm($array, "year", 2011, TRUE)); // removes all 2011

function remove_elm($arr, $key, $val, $within = FALSE) {
    foreach ($arr as $i => $array)
            if ($within && stripos($array[$key], $val) !== FALSE && (gettype($val) === gettype($array[$key])))
                unset($arr[$i]);
            elseif ($array[$key] === $val)
                unset($arr[$i]);

    return array_values($arr);
}

答案 3 :(得分:1)

对于单个已知值,将其放在迭代开始的多维数组中:

foreach ( $array as $subarray ) {
  //beginning of the loop where you do things with your array
  if ( $subarray->$key == '$valueToRemoveArrayBy' ) continue;
  //iterate your stuff
}

如果您的标准为真,则简单地跳过整个迭代。

或者你可以反过来做。根据口味,可能更容易阅读:

foreach ( $array as $subarray ) {
  if ( $subarray->$key != $valueToRemoveArrayBy ) {
    //do stuff 
  }
}

我不知道。也许这看起来很丑陋。不过我喜欢它。简短,快捷,简单。

在这种情况下看起来过滤的目的是打印出一些内容并根据某些标准跳过一些内容。如果你在循环之前进行过滤,你必须循环整个过程两次 - 一次过滤,一次打印内容。

如果你这样做,在循环内,这不是必需的。除了循环内部之外,您也不会更改数组,如果您不总是希望特别按这些条件进行过滤,这可能会有所帮助。

答案 4 :(得分:0)

你应该这样试试,
$ mainArray是您当前的数据
$ subArray是您要删除的数据

    foreach ($mainArray as $key => $mainData){
        foreach ($subArray as $subData){
            if($mainData['dataId'] == $subData['dataId']){
                unset($mainArray[$key]);
                break;
            }
        }
    }

    var_dump(array_values($mainArray));

这将为您提供所需的新数组索引。

答案 5 :(得分:0)

这是我实现的方式:

<?php 
    print_r($array);
    echo "<br><br>";
    foreach($array as $k => $v){
        echo "k: ".$k." v: ".$v."<br><br>";
        if(($v == 'Toronto') || ($v == 'London')){
            unset($array[$k]);
        }
    }
    echo "<br><br>";
    print_r($array);
?>

答案 6 :(得分:0)

function removeElementWithValue($array, $value){
    $temp=array(); //Create temp array variable.
    foreach($array as $item){ //access array elements.
        if($item['year'] != $value){ //Skip the value, Which is equal.
        array_push($temp,$item);  //Push the array element into $temp var.
        }
     }
     return $temp; // Return the $temp array variable.
}

//Simple code to delete element of multidimensional array.
$array = removeElementWithValue($array, "year");

答案 7 :(得分:0)

这是我解决此问题的方法:使用具有自定义功能的array_udiff将一个数组的元素中的“年份”(取消匹配)到“过滤器”数组的元素中。

function fn_year_filter($a, $b) {
    return (is_array($a) ? $a['year'] : $a) != (is_array($b) ? $b['year'] : $b);
}
$array = array_udiff($array, array('2011', '2020'), 'fn_year_filter');

使用PHP> 5.3的匿名函数甚至更简单

$array = array_udiff($array, array(2011, 2020), function($a, $b) {
    return (is_array($a) ? $a['year'] : $a) != (is_array($b) ? $b['year'] : $b);
});

* 请注意使用松散比较,因此它也适用于整数。