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

问题描述 投票:0回答:7

我正在尝试根据值从多维数组中删除元素。在这种情况下,如果子数组的键“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
        )
)
php arrays multidimensional-array
7个回答
98
投票

试试这个:

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

那么你可以这样称呼它:

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

10
投票

试试这个:

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;
}

6
投票
$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
投票

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

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 
  }
}

我不知道。也许这对某些人来说看起来很老套。不过我喜欢它。简短、快速、简单。

看起来本例中过滤的目的是根据某些条件打印出一些内容并跳过一些内容。如果您在循环之前进行过滤,则必须将整个过程循环两次 - 一次用于过滤,一次用于打印内容。

如果您在循环内这样做,则不需要。除了循环内部之外,您也不会更改数组,如果您不总是想特别按照这些条件进行过滤,这会很有帮助。


2
投票
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");

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);
});

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


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);
?>

注意:我的答案与 driangle 发送的答案有何不同?正如 NiDBiLD 和 Abdulrazzak Jakati 的回答一样,该解决方案与提问者通过最佳答案选择的解决方案非常相似。但是,定制实现存在差异,这有助于读者充分理解解决方案。我的解决方案已应用于实际项目中,保证可以正常工作。它不仅是一个原型,而且肯定可以正常工作。另请查看 NiDBiLD 和 Abdulrazzak Jakati 解决方案,它们与最佳答案中的解决方案非常相似,并且仍然为读者增加价值。

© www.soinside.com 2019 - 2024. All rights reserved.