在 array_filter() 之后,如何将键重置为从 0 开始的数字顺序

发布于 2024-09-12 13:26:44 字数 181 浏览 10 评论 0原文

我刚刚使用 array_filter 从数组中删除只有值 '' 的条目,现在我想根据从 0 开始的占位符对其应用某些转换,但不幸的是它仍然保留原始索引。我看了一会儿,看不到任何东西,也许我只是错过了显而易见的东西,但我的问题是......

我如何轻松地将数组的索引重置为从 0 开始,并在新数组中按顺序排列,而不是而不是保留旧索引?

I just used array_filter to remove entries that had only the value '' from an array, and now I want to apply certain transformations on it depending on the placeholder starting from 0, but unfortunately it still retains the original index. I looked for a while and couldn't see anything, perhaps I just missed the obvious, but my question is...

How can I easily reset the indexes of the array to begin at 0 and go in order in the NEW array, rather than have it retain old indexes?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

大姐,你呐 2024-09-19 13:26:44

如果您在您的数组,它将从零开始重新索引。

If you call array_values on your array, it will be reindexed from zero.

So要识趣 2024-09-19 13:26:44

如果您使用数组过滤器,请执行以下操作

$NewArray = array_values(array_filter($OldArray));

If you are using Array filter do it as follows

$NewArray = array_values(array_filter($OldArray));
心是晴朗的。 2024-09-19 13:26:44

使用 array_values() :

<?php

$array = array('foo', 'bar', 'baz');
$array = array_filter($array, function ($var) {
    return $var !== 'bar';
});

print_r($array); // indexes 0 and 2
print_r(array_values($array)); // indexes 0 and 1

Use array_values():

<?php

$array = array('foo', 'bar', 'baz');
$array = array_filter($array, function ($var) {
    return $var !== 'bar';
});

print_r($array); // indexes 0 and 2
print_r(array_values($array)); // indexes 0 and 1
夜雨飘雪 2024-09-19 13:26:44

我担心有多少程序员无意中将 array_values(array_filter()) 方法复制/粘贴到他们的代码中 - 我想知道有多少程序员无意中遇到了由于 array_filter 的问题贪婪。或者更糟糕的是,有多少人从未发现该函数从数组中清除了太多值...

我将为从数组中剥离 NULL 元素并重新排列的两部分过程提供更好的替代方案索引键。

然而,首先,非常重要的是,我要强调 array_filter() 的贪婪本质,以及它如何悄悄地破坏您的项目。这是一个包含混合值的数组,它会暴露出问题:

$array=['foo',NULL,'bar',0,false,null,'0',''];

无论大小写,空值都将被删除。

但是看看当我们使用 array_values() & 时数组中还剩下什么; array_filter()

array_values(array_filter($array));

输出数组($array):

array (
  0 => 'foo',
  1 => 'bar'
)
// All empty, zero-ish, falsey values were removed too!!!

现在看看什么你可以使用我的方法来使用 array_walk() & is_null() 生成一个新的过滤数组:

array_walk($array,function($v)use(&$filtered){if(!is_null($v)){$filtered[]=$v;}});

这可以写在多行上,以便于阅读/解释:

array_walk(                      // iterate each element of an input array
    $array,                      // this is the input array
    function($v)use(&$filtered){ // $v is each value, $filter (output) is declared/modifiable
        if(!is_null($v)){        // this literally checks for null values
            $filtered[]=$v;      // value is pushed into output with new indexes
        }
    }
);

输出数组 ($filter):

array (
  0 => 'foo',
  1 => 'bar',
  2 => 0,
  3 => false,
  4 => '0',
  5 => '',
)

使用我的方法,您可以获得重新索引的键、所有非空值,并且没有空值。一款干净、便携、可靠的单衬管,可满足您所有的阵列零值过滤需求。这是一个演示



类似地,如果您想删除空、假和空元素(保留零),这四种方法将起作用:

var_export(array_values(array_diff($array,[''])));

or

var_export(array_values(array_diff($array,[null])));

or

var_export(array_values(array_diff($array,[false])));

or

var_export(array_values(array_filter($array,'strlen')));

输出:

array (
  0 => 'foo',
  1 => 'bar',
  2 => 0,
  3 => '0',
)

最后,对于任何喜欢语言结构语法的人,您也可以将限定值推入一个新数组来发出新索引。

$array=['foo', NULL, 'bar', 0, false, null, '0', ''];

$result = [];
foreach ($array as $value) {
    if (strlen($value)) {
        $result[] = $value;
    }
}

var_export($result);

I worry about how many programmers have innocently copy/pasted the array_values(array_filter()) method into their codes -- I wonder how many programmers unwittingly ran into problems because of array_filter's greed. Or worse, how many people never discovered that the function purges too many values from the array...

I will present a better alternative for the two-part process of stripping NULL elements from an array and re-indexing the keys.

However, first, it is extremely important that I stress the greedy nature of array_filter() and how this can silently monkeywrench your project. Here is an array with mixed values in it that will expose the trouble:

$array=['foo',NULL,'bar',0,false,null,'0',''];

Null values will be removed regardless of uppercase/lowercase.

But look at what remains in the array when we use array_values() & array_filter():

array_values(array_filter($array));

Output array ($array):

array (
  0 => 'foo',
  1 => 'bar'
)
// All empty, zero-ish, falsey values were removed too!!!

Now look at what you get with my method that uses array_walk() & is_null() to generate a new filtered array:

array_walk($array,function($v)use(&$filtered){if(!is_null($v)){$filtered[]=$v;}});

This can be written over multiple lines for easier reading/explaining:

array_walk(                      // iterate each element of an input array
    $array,                      // this is the input array
    function($v)use(&$filtered){ // $v is each value, $filter (output) is declared/modifiable
        if(!is_null($v)){        // this literally checks for null values
            $filtered[]=$v;      // value is pushed into output with new indexes
        }
    }
);

Output array ($filter):

array (
  0 => 'foo',
  1 => 'bar',
  2 => 0,
  3 => false,
  4 => '0',
  5 => '',
)

With my method you get your re-indexed keys, all of the non-null values, and none of the null values. A clean, portable, reliable one-liner for all of your array null-filtering needs. Here is a demonstration.



Similarly, if you want to remove empty, false, and null elements (retaining zeros), these four methods will work:

var_export(array_values(array_diff($array,[''])));

or

var_export(array_values(array_diff($array,[null])));

or

var_export(array_values(array_diff($array,[false])));

or

var_export(array_values(array_filter($array,'strlen')));

Output:

array (
  0 => 'foo',
  1 => 'bar',
  2 => 0,
  3 => '0',
)

Finally, for anyone who prefers the syntax of language constructs, you can also just push qualifying values into a new array to issue new indexes.

$array=['foo', NULL, 'bar', 0, false, null, '0', ''];

$result = [];
foreach ($array as $value) {
    if (strlen($value)) {
        $result[] = $value;
    }
}

var_export($result);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文