【问题标题】:How to remove element from non-associative array in php如何从php中的非关联数组中删除元素
【发布时间】:2016-03-27 11:54:53
【问题描述】:

我正在尝试使用 unset 函数从 php 数组中删除特定元素。问题是当我 var_dump 数组时它显示所有索引(不好)但是如果我尝试 var_dump 特定索引 PHP 会抛出警告(好)。

$a = [
    'unset_me',
    'leave_me',
    'whatever',
];

unset($a['unset_me']);

var_dump($a);
/**
array(3) {
  [0]=>
  string(8) "unset_me"
  [1]=>
  string(8) "leave_me"
  [2]=>
  string(8) "whatever
*/
var_dump($a['unset_me']); // Undefined index: unset_me

问题是为什么php会有这样的行为以及如何正确删除索引?

【问题讨论】:

  • unset($a[0]); - 数组有数字索引,没有字符串索引为unset_me的元素

标签: php arrays unset


【解决方案1】:

另一种解决方案:

$arr = array('unset_me','leave_me','whatever',);  
print_r($arr);

// remove the elements that you want  
$arr = array_diff($arr, array("unset_me"));
print_r($arr);  

【讨论】:

  • 这比涉及array_search 的任何事情都要好。更简单,故障点更少,对阵列结构的破坏性更小。
  • 如果数组中包含数组或对象,由于数组/对象到字符串的转换,此方法会导致错误。对于一般用途来说,这不是一个很好的解决方案。
【解决方案2】:

你可以试试array_search -

unset($a[array_search('unset_me', $a)]);

如果需要,然后添加检查 -

if(array_search('unset_me', $a) !== false) {
    unset($a[array_search('unset_me', $a)]);
}

Demo

【讨论】:

  • @Steve 如果正确添加了检查,一切都会好起来的。您可以检查更新。我已经提到过它。这是因为array_search 返回falsefalse 被视为0。 :)
  • @Sougata:你是最好的……最活跃的人。
【解决方案3】:
$arr = array('unset_me','leave_me','whatever',);  
print_r($arr);
echo '<br/>';

$key = array_search('unset_me', $arr);
if($key !== false)
unset($arr[$key]);

print_r($arr);

【讨论】:

    【解决方案4】:

    我最近遇到了这个问题,发现这个解决方案有帮助:

    unset($a[array_flip($a)['unset_me']]);

    只是为了解释这里发生了什么:

    array_flip($a) 切换键的项目。所以它会变成:

    $a = [
        'unset_me' => 0,
        'leave_me' => 1,
        'whatever' => 2,
    ];
    

    array_flip($a)['unset_me'] 因此解析为 0。因此该表达式被放入原始的 $a,然后可以取消设置。

    这里有两个警告:

    • 这仅适用于您的基本数组,如果您有一组对象或数组,那么您需要选择其他解决方案之一

    • 您删除的键将从数组中丢失,因此在这种情况下,0 将没有项目,并且数组将从 1 开始。如果对您很重要,您可以通过array_values($a) 重置密钥。

    【讨论】:

      猜你喜欢
      • 2011-07-23
      • 2017-01-14
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      • 2012-12-19
      • 2011-12-31
      相关资源
      最近更新 更多