PHP 从关联数组中删除元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5450148/
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 21:28:34  来源:igfitidea点击:

PHP Remove elements from associative array

phparrays

提问by user648198

I have an PHP array that looks something like this:

我有一个看起来像这样的 PHP 数组:

Index              Key     Value
[0]                1       Awaiting for Confirmation
[1]                2       Assigned
[2]                3       In Progress
[3]                4       Completed
[4]                5       Mark As Spam

When I var_dump the array values i get this:

当我 var_dump 数组值时,我得到了这个:

array(5) { [0]=> array(2) { ["key"]=> string(1) "1" ["value"]=> string(25) "Awaiting for Confirmation" } [1]=> array(2) { ["key"]=> string(1) "2" ["value"]=> string(9) "Assigned" } [2]=> array(2) { ["key"]=> string(1) "3" ["value"]=> string(11) "In Progress" } [3]=> array(2) { ["key"]=> string(1) "4" ["value"]=> string(9) "Completed" } [4]=> array(2) { ["key"]=> string(1) "5" ["value"]=> string(12) "Mark As Spam" } }

I wanted to remove Completedand Mark As Spam. I know I can unset[$array[3],$array[4]), but the problem is that sometimes the index number can be different.

我想删除CompletedMark As Spam。我知道我可以unset[$array[3],$array[4]),但问题是有时索引号可能不同。

Is there a way to remove them by matching the value name instead of the key value?

有没有办法通过匹配值名称而不是键值来删除它们?

回答by Pascal MARTIN

Your array is quite strange : why not just use the keyas index, and the valueas... the value ?

你的数组很奇怪:为什么不直接使用keyas 索引和valueas... 值?

Wouldn't it be a lot easier if your array was declared like this :

如果你的数组是这样声明的,会不会容易很多:

$array = array(
    1 => 'Awaiting for Confirmation', 
    2 => 'Asssigned', 
    3 => 'In Progress', 
    4 => 'Completed', 
    5 => 'Mark As Spam', 
);

That would allow you to use your values of keyas indexes to access the array...

这将允许您使用key作为索引的值来访问数组...

And you'd be able to use functions to search on the values, such as array_search():

您可以使用函数来搜索值,例如array_search()

$indexCompleted = array_search('Completed', $array);
unset($array[$indexCompleted]);

$indexSpam = array_search('Mark As Spam', $array);
unset($array[$indexSpam]);

var_dump($array);

Easier than with your array, no ?

比你的阵列更容易,不是吗?





Instead, with your array that looks like this :

相反,您的数组如下所示:

$array = array(
    array('key' => 1, 'value' => 'Awaiting for Confirmation'), 
    array('key' => 2, 'value' => 'Asssigned'), 
    array('key' => 3, 'value' => 'In Progress'), 
    array('key' => 4, 'value' => 'Completed'), 
    array('key' => 5, 'value' => 'Mark As Spam'), 
);

You'll have to loop over all items, to analyse the value, and unset the right items :

您必须遍历所有项目,分析value和取消设置正确的项目:

foreach ($array as $index => $data) {
    if ($data['value'] == 'Completed' || $data['value'] == 'Mark As Spam') {
        unset($array[$index]);
    }
}
var_dump($array);

Even if do-able, it's not that simple... and I insist : can you not change the format of your array, to work with a simpler key/value system ?

即使可行,也不是那么简单……我坚持认为:您不能更改数组的格式以使用更简单的键/值系统吗?

回答by ADFS

  ...

  $array = array(
      1 => 'Awaiting for Confirmation', 
      2 => 'Asssigned', 
      3 => 'In Progress', 
      4 => 'Completed', 
      5 => 'Mark As Spam', 
  );



  return array_values($array);
  ...

回答by Dejan Marjanovic

$key = array_search("Mark As Spam", $array);
unset($array[$key]);

For 2D arrays...

对于二维数组...

$remove = array("Mark As Spam", "Completed");
foreach($arrays as $array){
    foreach($array as $key => $value){
        if(in_array($value, $remove)) unset($array[$key]);
    }
}

回答by Anirban Das

You can use this

你可以用这个

unset($dataArray['key']);

回答by Mikel Annjuk

Why do not use array_diff?

为什么不使用array_diff?

$array = array(
    1 => 'Awaiting for Confirmation', 
    2 => 'Asssigned', 
    3 => 'In Progress', 
    4 => 'Completed', 
    5 => 'Mark As Spam', 
);
$to_delete = array('Completed', 'Mark As Spam');
$array = array_diff($array, $to_delete);

Just note that your array would be reindexed.

请注意,您的数组将被重新索引。

回答by Alp

Try this:

尝试这个:

$keys = array_keys($array, "Completed");

/edit As mentioned by JohnP, this method only works for non-nested arrays.

/edit 正如 JohnP 所提到的,此方法仅适用于非嵌套数组。

回答by Roger Kaplan

I kinda disagree with the accepted answer. Sometimes an application architecture doesn't want you to mess with the array id, or makes it inconvenient. For instance, I use CakePHP quite a lot, and a database query returns the primary key as a value in each record, very similar to the above.

我有点不同意接受的答案。有时,应用程序架构不希望您弄乱数组 id,或者让它不方便。比如我经常使用CakePHP,一个数据库查询返回主键作为每条记录中的一个值,非常类似于上面的。

Assuming the array is not stupidly large, I would use array_filter. This will create a copy of the array, minus the records you want to remove, which you can assign back to the original array variable.

假设数组不是很大,我会使用array_filter。这将创建一个数组副本,减去要删除的记录,您可以将其分配回原始数组变量。

Although this may seem inefficient it's actually very much in vogue these days to have variables be immutable, and the fact that most php array functions return a new array rather than futzing with the original implies that PHP kinda wants you to do this too. And the more you work with arrays, and realize how difficult and annoying the unset() function is, this approach makes a lot of sense.

尽管这看起来效率低下,但实际上现在非常流行让变量保持不变,而且大多数 php 数组函数返回一个新数组而不是原始数组的事实意味着 PHP 有点希望您也这样做。您使用数组的次数越多,并意识到 unset() 函数是多么困难和烦人,这种方法就很有意义。

Anyway:

反正:

$my_array = array_filter($my_array, 
                         function($el) { 
                            return $el["value"]!="Completed" && $el!["value"]!="Marked as Spam"; 
                         });

You can use whatever inclusion logic (eg. your id field) in the embedded function that you want.

您可以在您想要的嵌入函数中使用任何包含逻辑(例如您的 id 字段)。

回答by Nitish Pandey

The way to do this to take your nested target array and copy it in single step to a non-nested array. Delete the key(s) and then assign the final trimmed array to the nested node of the earlier array. Here is a code to make it simple:

这样做的方法是获取嵌套的目标数组并将其一步复制到非嵌套数组。删除键,然后将最终修剪过的数组分配给较早数组的嵌套节点。下面是一段代码,让它变得简单:

$temp_array = $list['resultset'][0];

unset($temp_array['badkey1']);
unset($temp_array['badkey2']);

$list['resultset'][0] = $temp_array;

回答by Ivan Proskuryakov

for single array Item use reset($item)

用于单个数组项使用 reset($item)