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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4466159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:07:03  来源:igfitidea点击:

Delete element from multidimensional-array based on value

phparraysmultidimensional-array

提问by Bob

I'm trying to delete elements from a multidimensional-array based on a value. In this case if a sub-array's key 'year' has the value 2011 I want that sub-array out.

我正在尝试根据值从多维数组中删除元素。在这种情况下,如果子数组的键 'year' 的值为 2011,我想要该子数组。

Just for the record: i'm running PHP 5.2.

只是为了记录:我正在运行 PHP 5.2。

My array looks like this:

我的数组如下所示:

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

回答by driangle

Try this:

尝试这个:

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

Then you would call it like this:

然后你会这样称呼它:

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

回答by Jacob Relkin

Try this:

尝试这个:

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

回答by ifaour

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

回答by NiDBiLD

For a single, known value, put this in beginning of iteration through the multidimensional array:

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

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

Simply skips that entire iteration if your criteria are true.

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

Alternately you could do the reverse. Might be easier to read, depending on taste:

或者你可以反过来做。可能更容易阅读,具体取决于口味:

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

I dunno. Maybe this looks hacky to some. I like it, though. Short, quick and simple.

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

Looked like the purpose of filtering in this case was to print out some contents and skip some, based on certain criteria. If you do the filtering before the loop, you'll have to loop through the entire thing twice - once to filter and once to print the contents.

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

If you do it like this, inside the loop, that is not required. You also won't alter your array except for inside of the loop, which can be helpful if you don't always want to filter by these criteria in particular.

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

回答by MAULIK MODI

You should try this way,
$mainArray is your current data
$subArray is the data you want to remove

你应该这样试试,
$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));

This will give you output you wanted with new index of array.

这将为您提供您想要的带有新数组索引的输出。

回答by Jaime Montoya

This is how I achieved it:

这就是我实现它的方式:

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

回答by Abdulrazzak Jakati

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

回答by nobug

Here is my approach to this problem: use array_udiffwith custom function to (un-)match 'year' from one array's elements to the elements of the "filter" array.

这是我解决这个问题的方法:使用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');

And even simpler with the anonymous functions of PHP > 5.3

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

* Note the use of loose comparison, hence it works with integers too.

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